如何使用python3替换列表列表中的元素?
txt =[[""],[""],[""]]
for i in txt:
x = i.replace("", "apples")
print(x)
预期输出:
apples
apples
apples
答案 0 :(得分:1)
要替换主列表""
的子列表中txt
的每个实例,可以使用以下列表理解:
txt =[[""],[""],[""]]
txt = [[x if not x=="" else 'apples' for x in sublist] for sublist in txt]
产生:
[['apples'], ['apples'], ['apples']]
您现在拥有的代码无法使用,因为给定您在txt
上循环的方式,i
是子列表,而python列表对象没有.replace
方法。
答案 1 :(得分:0)
def replace(value, new_value, outer_list):
for inner_list in outer_list:
for i,element in enumerate(inner_list):
if element == value:
inner_list[i]= new_value
return outer_list
txt =[[""],[""],[""]]
txt = replace("", "apple", txt)
此功能可以满足您的需求
答案 2 :(得分:0)
尝试这个:
txt = [[""],[""],[""]]
for i in range(len(txt)):
for ii in range(len(txt[i])):
txt[i][ii] = (txt[i][ii]).replace("","apples")
print(txt)
答案 3 :(得分:0)
使用列表理解:
txt =[[""],[""],[""]]
print([[x if x != "" else 'apples' for x in sub] for sub in txt])
输出:
[['apples'], ['apples'], ['apples']]
要分别打印;
txt = [[x if x != "" else 'apples' for x in sub] for sub in txt]
for sub in txt:
for elem in sub:
print(elem)
输出:
apples
apples
apples