【问题标题】:Python trouble with lists列表的 Python 问题
【发布时间】:2014-03-21 21:26:00
【问题描述】:

我有一组来自 a->i 的初始变量、一个完整的变量列表、一个单独的整数值列表和一组由初始变量子集组成的列表:

a=0
b=0
...
i=0

exampleSubList_1 = [c, e, g]
fullList = [a, b, c, d, e, f, g, h, i] #The order of the list is important
otherList = [2, 4, 6, 8, 10, 12, 14, 16, 18] #The order of the list is important

我希望我的程序读取输入 exampleList_X 并在fullList中找到其对应的索引条目,并使用该索引号输出otherList中的对应值。比如……

exampleList_1[0]
#Which is c
#It should find index 2 in fullList
#Entry 2 in otherList is the value 6.
#So it should output
6

这可能吗?我愿意使用元组/字典。

为了清楚起见,这是针对使用 LED 的 Raspberry Pi noughts and crosses 游戏项目。 c、e、g对应从右上到左下的对角线的获胜条件,otherList对应的是树莓派上发出电流点亮LED的引脚。

【问题讨论】:

  • 你考虑过from collections import OrderedDict吗? ``
  • @GWW,我已经尝试了各种零碎的东西,但是在尝试将 fullList 与 otherList 进行比较时,我一直卡住。
  • @Dietrich,我试过 Dict,但我没有听说过 OrderedDict。我会看看然后回来找你
  • OP:目前exampleSubList_1[0,0,0],所以fullList.index(exampleSubList_1[0]) == 0 因为你所有的变量ai 都是0,所以没有区别它们。你是说exampleSubList_1 = ['c','e','g'], fullList = ['a','b','c', ... , 'i'] 吗?
  • @Dietrich,我看过文档,但不是特别清楚。我是否以与 dict 相同的方式启动orderdict,并且对键/值执行相同的命令仍然有效?

标签: python list python-3.x


【解决方案1】:

列表理解:

results = [otherList[fullList.index(c)] for c in exampleSubList_1]

results 将返回:

[6, 10, 14]

或者一个简单的for循环:

for c in exampleSubList_1:
    print otherList[fullList.index(c)]

应该打印

6
10
14

【讨论】:

  • 嗯,我看看再回复你
【解决方案2】:
>>> symbol_pos_map = {v:k for k,v in enumerate(fullList)}
>>> otherList[symbol_pos_map[exampleSubList_1[0]]]
6

不要使用list.index,因为它每次都会进行线性搜索,首先以线性成本将fullList映射到字典,然后后续查找是一个常数时间。

【讨论】:

  • 对于任何寻找 OP 似乎在问什么的人来说,这是一个有用的优化。 (OP 在 cmets 中说,预期的输出是实际的变量名称。您的答案仍然是有效阅读问题的好答案。)
【解决方案3】:

你真的应该考虑使用字典。

考虑:

l1 = ['c', 'e', 'g']
l2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
l3 = [2, 4, 6, 8, 10, 12, 14, 16, 18]

results = [l3[l2.index(c)] for c in l1]
print "results 1:", results

d1 = {'a': 2, 'b': 4, 'c': 6, 'd':8, 'e': 10, 'f': 12, 'g': 14, 'h': 16, 'i': 18}
results = [d1[c] for c in l1]
print "results 2:", results

那些给你同样的结果。让字典完成它的设计目的:查找一个键,然后返回一个值。

请注意,键值几乎可以是任何东西:数字、字母、完整字符串、值元组...

如果您已经有了两个“查找列表”(在我的示例中为 l2 和 l3),那么您可以使用 dict() 和 zip() 函数为您创建字典:

d2 = dict(zip(l2, l3))  # this creates a dictionary identical to d1
results = [d2[c] for c in l1]
print "results 3:", results

【讨论】:

  • 我试过了,但 Dict 不保留您输入变量的顺序:dft.ba/-N_lists2
  • @pingk 为什么需要保留订单?在您的帖子中,您似乎使用顺序来保持两个列表“有组织”,以便相同索引处的值相关;但是使用 dict,您只需使用 dict 本身来关联两个数据集。我的建议产生了你说你需要的结果,而不需要保持列表的顺序!
【解决方案4】:

在阅读了字典之后,我发现使用 OrderedDict 非常适合我的需要,请参阅 Python select ith element in OrderedDict

@Dietrich 感谢您的想法。

【讨论】:

    【解决方案5】:

    可以使用 list.index(x) 方法,当然您可以访问列表中的任何元素,只需编写 list[index]

    【讨论】:

    • 你能给我一个例子来说明它在实践中是如何工作的吗?我发现如果我使用字典,我可以找到 fullList 中的索引,但是我在尝试将信息翻译到 otherList 时遇到了困难。
    猜你喜欢
    • 2023-04-04
    • 2011-12-16
    • 2012-03-11
    • 1970-01-01
    • 2016-02-22
    • 2011-07-09
    • 2015-09-29
    • 2020-09-29
    • 2013-01-07
    相关资源
    最近更新 更多