Python 如何在两个列表中搜索配对?
我有两个主要列表,每个列表包含10个字符串:Python 如何在两个列表中搜索配对?,python,string,list,Python,String,List,我有两个主要列表,每个列表包含10个字符串: bus0 = ['North', 'North','North','North', 'East', 'East', 'East', 'west','west', 'south'] bus1 = ['East', 'west', 'south','northeast', 'west', 'south', 'northeast', 'south', 'northeast', 'northeast'] 这些列表基本上包含方向的可能组合,因此基本上,bus
bus0 = ['North', 'North','North','North', 'East', 'East', 'East', 'west','west', 'south']
bus1 = ['East', 'west', 'south','northeast', 'west', 'south', 'northeast', 'south', 'northeast', 'northeast']
这些列表基本上包含方向的可能组合,因此基本上,bus0
中第0个位置的元素将在bus1
中的相同位置(第0个)具有可能的对,最重要的是组合是唯一的,例如,除了在0位置
之外,在任何其他位置都找不到东北
或东北
。
我有另一个包含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]
输出
[45, 23, 133]
嘿,谢谢你。