a = [['12','0.4'],['13','0.4'],['14','0.4']]
b = ['122','133', '144']
for item in a:
for item[0] in item:
if item in b:
replace b for item
output:
a = [['122','0.4'],['133','0.4'],['144','0.4']]
答案 0 :(得分:4)
尝试:
a = [['12','0.4'],['13','0.4'],['14','0.4']]
b = ['122','133', '144']
for list_a in a:
for item_b in b:
if list_a[0] in item_b :
list_a[0] = item_b
break
print(a)
>>> [['122', '0.4'], ['133', '0.4'], ['144', '0.4']]
答案 1 :(得分:0)
for item in a:
for i in range(len(b)):
if item[0] in b[i]:
item[0] = b[i]
break
Output: a = [['122', '0.4'], ['133', '0.4'], ['144', '0.4']].
你应该在python中阅读“for”循环,这是非常基本的。
答案 2 :(得分:0)
使用带有后退值的next()
的列表理解也可以解决问题:
a = [[next((r for r in b if x in r), x), y] for x, y in a]
打印所需的内容:
[['122', '0.4'], ['133', '0.4'], ['144', '0.4']]
鉴于next()
短路,这种方法完全等同于具有2 for
个循环和break
的方法,但更短且非常小就像可读......