Python列表问题

时间:2014-03-21 21:26:00

标签: python list python-3.x

我有一组来自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和crosses游戏项目。 c,e和g对应于从右上角到左下角的对角线的获胜条件,而otherList对应于Raspberry Pi上的引脚,该引脚发出电流以点亮LED。

5 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

>>> symbol_pos_map = {v:k for k,v in enumerate(fullList)}
>>> otherList[symbol_pos_map[exampleSubList_1[0]]]
6

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

答案 2 :(得分:1)

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

考虑:

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

答案 3 :(得分:0)

阅读完字词后,我发现使用OrderedDict可以完美地满足我的需求,请参阅Python select ith element in OrderedDict

@Dietrich感谢你的想法。

答案 4 :(得分:-1)

可以使用list.index(x)方法,当然你只需要编写列表[index]

就可以访问列表中的任何元素