我必须编写一个程序来获取一个项目(链接到另一个列表(进入列表的时间,我写了一个例子来理解:我有两个清单:
l=[13,14,8,13,13,14,14,8,13]和l1=['pea','rpai','rpai','schai','pea','rpe','zoi','zui','briai','lpe']
现在,l的每一项都只在l1的一项上链接(所以13-"pea",14-"pai"ecc(,就像双射函数一样。我想要创建第三列表l2,其将1个数字与所有相等的"0"相关联;元组";(es。13-‘pea’=1,14-‘pai’=2(所以如果在循环中我再次遇到另一个相等的元组,我直接链接相关的数字(所以如果我再次像l1的第四个元素一样获得13-‘pee’,我将再次链接数字1(。。。这就是我创造的,但它似乎奏效了,有人能让我明白出了什么问题吗?感谢
for i in lista:
if i not in pro:
pro.append(i)
l2.append(conta)
d[i[1]]=conta
conta+=1
else:
a=d.get(i[1])
l2.append(a)
现在";lista";是包含两个列表的元组的列表(所以类似于=[(13,'pea(,(14,'rpai'(ecc]pro是一个初始的空列表,l2是最终结果,d是我用来从l元素和l1创建连接的dict(d={13:0,14:1…}(,但我不明白errror在哪里,有什么建议吗?谢谢
这能解决您的问题吗?
l = [13, 14, 14, 8, 13, 13, 14, 14, 8, 13]
l1 = ['pea', 'rpai', 'rpai', 'schiai', 'pea',
'rpe', 'zoi', 'zoi', 'briai ', 'rpe']
final = []
for num, item in zip(l, l1):
final.append((num, l1.index(item)))
print(final)
输出:
[(13, 0), (14, 1), (14, 1), (8, 3), (13, 0), (13, 5), (14, 6), (14, 6), (8, 8), (13, 5)]
我仍然不能100%确定我是否正确理解了你,但这符合你的要求吗?
numbers = [13, 14, 14, 8, 13, 13, 14, 14, 8, 13]
items = ['pea', 'rpai', 'rpai', 'schiai', 'pea', 'rpe', 'zoi', 'zoi', 'briai ', 'rpe']
# we build a list tuples where the i-th tuple consists of the i-th number and the i-th item
tuples = zip(numbers, items) # [(13, "pea"), (14, "rpai"), (14, "rpai"), ... ]
# now we associate an index to each of those combinations (=tuples)
index = {}
index_increment = 0
for t in tuples:
if t not in index:
index[t] = index_increment
index_increment += 1
# print the results
for t, i in index.items():
print(f'{t}: {i}')
输出:
(13, 'pea'): 0
(14, 'rpai'): 1
(8, 'schiai'): 2
(13, 'rpe'): 3
(14, 'zoi'): 4
(8, 'briai '): 5