[英]How to search for the pair in two lists?
我有两个主要列表,每个列表包含 10 个字符串:
bus0 = ['North', 'North','North','North', 'East', 'East', 'East', 'west','west', 'south']
bus1 = ['East', 'west', 'south','northeast', 'west', 'south', 'northeast', 'south', 'northeast', 'northeast']
这些列表基本上包含方向的可能组合,所以基本上,出现在bus0
中第 0 个 position 的元素将在bus1
中的相同位置(第 0 个)具有可能的对,最重要的是组合是唯一的,例如,除了0th position
position 之外,您不会在任何其他 position 找到North-East
或East-North
。 我有另一个包含 10 个数字的列表。
data = [12, 23, 34, 45,13, 133, 324, 475,94,66]
现在有两个对列表,它基本上告诉我们需要在bus0
和bus1
中搜索哪对。
pair1 = ['north', 'north', 'south']
pair2 = ['northeast', 'west', 'east']
所以从技术上讲,会有三对:
现在要从data
列表中获取数据,我只需要从这些位置中选择元素。 我的方法:
bus0 = ['North', 'North','North','North', 'East', 'East', 'East', 'west','west', 'south']
bus1 = ['East', 'west', 'south','northeast', 'west', 'south', 'northeast', 'south', 'northeast', 'northeast']
data = [12, 23, 34, 45,13, 133, 324, 475,94,66]
bus0 = [i.lower() for i in bus0]
bus1 = [i.lower() for i in bus1]
combine = [(i,j,k) for i,j,k in zip(bus0, bus1, data)]
pair1 = ['north', 'north', 'south']
pair2 = ['northeast', 'west', 'east']
for i in combine:
for k,l in zip(pair1, pair2):
if i[0]==k and i[1]==l:
print(i[0]+'-'+ k)
print(i[0] + '-' + l)
print(i[2])
谁能帮忙?
您可以创建一个字典,其中键是两个列表的排序值,然后创建两个对列表的排序值并查找值。
bus0 = ['North', 'North','North','North', 'East', 'East', 'East', 'west','west', 'south']
bus1 = ['East', 'west', 'south','northeast', 'west', 'south', 'northeast', 'south', 'northeast', 'northeast']
data = [12, 23, 34, 45,13, 133, 324, 475,94,66]
pair1 = ['north', 'north', 'south']
pair2 = ['northeast', 'west', 'east']
pairs = ['-'.join(sorted([x.lower(), y.lower()])) for x,y in zip(pair1,pair2)]
m = dict(zip(['-'.join(sorted([x.lower(),y.lower()])) for x,y in zip(bus0,bus1)],data))
[m[x] for x in pairs]
Output
[45, 23, 133]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.