“ for”循环无法正确循环

时间:2020-07-24 02:14:39

标签: python loops

a=[['kyle','movie_1','c_13'],
   ['blair','food','a_29'],
   ['reese','movie_2','abc_76']]

b=['df.movie_1',
   'ghk.food',
   'df.movie_2']

x = {}
for i in b:
    y = i.split('.')
    for j in a:
        if y[1] in j : x[y[0]]=j

print(x)

这是我的代码,用于检查列表a中是否有字符串。 我得到的输出是

{'df': ['reese', 'movie_2', 'abc_76'], 'ghk': ['blair', 'food', 'a_29']}

我想要的输出是

{'df': [['kyle','movie_1','c_13'],['reese', 'movie_2', 'abc_76']], 'ghk': ['blair', 'food', 'a_29']}

3 个答案:

答案 0 :(得分:3)

原因是该值在存在x['df']时将被覆盖。

您可以使用defaultdict保存它们(尽管与您的预期有所不同,但这很容易):

from collections import defaultdict
a = [['kyle', 'movie_1', 'c_13'],
     ['blair', 'food', 'a_29'],
     ['reese', 'movie_2', 'abc_76']]

b = ['df.movie_1',
     'ghk.food',
     'df.movie_2']

x = defaultdict(list)
for i in b:
    y = i.split('.')
    for j in a:
        if y[1] in j:
            x[y[0]].append(j)

print(x)
# defaultdict(<class 'list'>, {'df': [['kyle', 'movie_1', 'c_13'], ['reese', 'movie_2', 'abc_76']], 'ghk': [['blair', 'food', 'a_29']]})

答案 1 :(得分:0)

如先前的答案中所述,问题在于循环最终会覆盖x[y[0]]的值。根据所需的输出,您需要的是改为appendlist。使用defaultdict已经是一个不错的解决方案。相反,如果您只想使用标准list,则这是一种方法:

a = [
      ['kyle','movie_1','c_13'],
      ['blair','food','a_29'],
      ['reese','movie_2','abc_76']]

b = [
      'df.movie_1',
      'ghk.food',
      'df.movie_2']

x = {}
for i in b:
    y = i.split('.')
    for j in a:
        if y[1] in j:
          if y[0] not in x:  # if this is the first time we append
            x[y[0]] = []     # make it an empty list
          x[y[0]].append(j)  # then always append

print(x)

答案 2 :(得分:0)

希望如此: 一行代码

代码:

op_dict={}
[op_dict.setdefault(x.split('.')[0], []).append(y) for x in b for y in a if x.split('.')[1] in y]

输出: Output lookslike

相关问题