在lis中关联两个项目

2024-06-02 07:55:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在比较两个列表中的公共字符串,我的代码目前正在从两个列表中输出公共项。在

列表1

['5', 'orange', '20', 'apple', '50', 'blender']

列表2

^{pr2}$

以下是我目前为止的代码:

for item1 in list1[1::2]:
    for item2 in list2[1::2]:
        if item1 == item2:
            print(item1)

这个代码将返回blender。我现在要做的是在每个列表中打印混合器之前的数字,以获得类似于以下内容的输出:

blender, 50, 25

我尝试向for循环添加两行新行,但没有获得所需的输出:

for item1 in list1[1::2]:
    for item2 in list2[1::2]:
        for num1 in list1[0::2]:
            for num2 in list2[0::2]:
               if item1 == item2:
                   print(item1, num1, num2)

我现在知道做循环不是答案。同时尝试调用item1[-1]也不起作用。我是Python新手,需要一些帮助!在

谢谢你


Tags: 字符串代码in列表forifprintblender
3条回答

我认为你更适合用字典来解决这个问题。。在

dict1 = {'orange': 5, 'apple': 20, 'blender': 50}
dict2 = {'blender': 25, 'pear': 20, 'spatula': 40}

所以要得到你想要的结果

^{pr2}$

所以如果你想以你想要的格式从每个字典中得到混合机的数量,你可以使用

print("blender, "+str(dict1['blender'])+", "+str(dict2['blender']))

更进一步,根据dict1dict2中的内容输出

for i in dict1.keys(): #dict1.keys() is essentially a list with ['orange','apple','blender']
    if i in dict2.keys(): #same deal, but different items in the list
        print(str(i)+", "+str(dict1[i])+", "+str(dict2[i])) #this outputs items that are in BOTH lists
    else:
        print(str(i)+", "+str(dict1[i])) #this outputs items ONLY in dict1
for i in dict2.keys():
    if i not in dict1.keys(): #we use not since we already output the matching in the previous loop
        print(str(i)+", "+str(dict2[i])) #this outputs items ONLY in dict2

输出:

orange, 5
apple, 20
blender, 50, 25
pear, 20
spatula, 40

你可以用两种方法来做,要么保持列表(这更麻烦):

list1 = ['5', 'orange', '20', 'apple', '50', 'blender']
list2 = ['25', 'blender', '20', 'pear', '40', 'spatula']
for item1 in list1[1::2]:
  for item2 in list2[1::2]:
    if item1 == item2:
       item_to_print = item1
       print(item1, ",", end="")
       for index in range(len(list1)):
           if list1[index] == item1:
               print(list1[index - 1], ",", end="")
       for index in range(len(list2)):
           if list2[index] == item1:
               print(list2[index - 1])

或者用字典更好的方法(在我看来):

^{pr2}$

两者都将输出:

>> blender , 50 , 25

你用错误的数据结构来处理这个问题。如果要在两者之间进行查找,则不应将此数据保存在列表中。相反,在这里使用字典会容易得多。在

设置

您可以使用zip来创建这两个词典:

a = ['5', 'orange', '20', 'apple', '50', 'blender']
b = ['25', 'blender', '20', 'pear', '40', 'spatula']

dct_a = dict(zip(a[1::2], a[::2]))
dct_b = dict(zip(b[1::2], b[::2]))

这将留给您以下两个字典:

^{pr2}$

这会使你的问题更容易解决。例如,要查找公用密钥:

common = dct_a.keys() & dct_b.keys()
# {'blender'}

以及查找与每个公用密钥匹配的所有值:

[(k, dct_a[k], dct_b[k]) for k in common]

输出:

[('blender', '50', '25')]

相关问题 更多 >