Python3:列表和字典。我如何创建一个字典,告诉我每个项目都来自哪个列表?

Python3:列表和字典。我如何创建一个字典,告诉我每个项目都来自哪个列表?,python,python-3.x,list,function,dictionary,Python,Python 3.x,List,Function,Dictionary,鉴于这两份清单: lst_1=['Apple', 'pie', 'is', 'the', 'most', 'delicious'] #list 1 lst_2=['It', 'is', 'Americas', 'best'] #list 2 如何将它们放在字典中,让它告诉我它来自哪个列表(1或2),如下所示: d['Apple'] = [1] #"Apple "is in list 1 d['pie']=[1] #"pie" is in list 1 d['is']=[1,2] #"i

鉴于这两份清单:

lst_1=['Apple', 'pie', 'is', 'the', 'most', 'delicious'] #list 1
lst_2=['It', 'is', 'Americas', 'best'] #list 2
如何将它们放在字典中,让它告诉我它来自哪个列表(1或2),如下所示:

d['Apple'] = [1] #"Apple "is in list 1
d['pie']=[1]     #"pie" is in list 1
d['is']=[1,2] #"is" is in list 1 and 2
d['It']=[2]   # "It" is in list 2
lst_1=['Apple', 'pie', 'is', 'the', 'most', 'delicious']
lst_2=['It', 'is', 'Americas', 'best']

dic={}
joined_list= lst_1 + lst_2
for e in joined_list:
    if e in lst_1 and e in lst_2:
        dic[e] = [1, 2]
    elif e in lst_1:
        dic[e] = [1]
    elif e in lst_2:
        dic[e] = [2]
print(dic)

您可以尝试以下操作:

d= {}
lst = set(lst_1 + lst_2)
for i in lst:
    if i in lst_1 and i in lst_2:
        d[i] = [1,2]
    elif i in lst_2:
        d[i] = [2]
    elif i in lst_1:
        d[i] = [1]
print(d)
lst_1=['Apple'、'pie'、'is'、'the'、'most'、'delicious']#列表1
lst#U 2=[‘它’、‘是’、‘美洲’、‘最好’]#列表2
d={}
对于索引,枚举中的i([lst_1,lst_2]):
对于i中的j:
d、 setdefault(j,set([]))
d[j].添加(索引+1)
印刷品(d)

使用
defaultdict

from collections  import defaultdict
lst_1=['Apple', 'pie', 'is', 'the', 'most', 'delicious'] #list 1
lst_2=['It', 'is', 'Americas', 'best'] #list 2
d = defaultdict(list)
for i in lst_1:
    d[i].append(1)
for i in lst_2:
    d[i].append(2)
dict(d)

{'Apple': [1], 'pie': [1], 'is': [1, 2], 'the': [1], 'most': [1], 'delicious': [1], 'It': [2], 'Americas': [2], 'best': [2]}
那么这个呢:

myDictionary= {
  "list1" : {
    "1" : "Apple",
    "2" : "pie",
    "3" : "is",
    "4" : "most",
    "5" : "delicious."
  },
  "list2" : {
    "1" : "It",
    "2" : "is",
    "3" : "America's",
    "4" : "best,"
  }
}

我希望它能起作用。

您可以使用dict理解来形成
dict
对象:

d={i : [1] for i in lst_1}
d.update({i: d.get(i, []) + [2] for i in lst_2})

您可以这样做:

d['Apple'] = [1] #"Apple "is in list 1
d['pie']=[1]     #"pie" is in list 1
d['is']=[1,2] #"is" is in list 1 and 2
d['It']=[2]   # "It" is in list 2
lst_1=['Apple', 'pie', 'is', 'the', 'most', 'delicious']
lst_2=['It', 'is', 'Americas', 'best']

dic={}
joined_list= lst_1 + lst_2
for e in joined_list:
    if e in lst_1 and e in lst_2:
        dic[e] = [1, 2]
    elif e in lst_1:
        dic[e] = [1]
    elif e in lst_2:
        dic[e] = [2]
print(dic)

@卢拉贝尔95看看这个