我想克隆 list1 中的每个元组,以便元组 [1, 0, 1]
中的列表被克隆为与原始元组恰好有一个不同的数字,这样它添加到新列表以使其:
[([0, 0, 1], 'a'), ([0, 1, 1], 'a'), ([1, 0, 0], 'a')]
但是,它返回给我的是
[[[0, 1, 0], 'a'], [[0, 1, 0], 'a'], [[0, 1, 0], 'a']].
list1 = [([1, 0, 1], 'a')]
list2 = list1.copy()
newlist = []
for x in list2:
for i in range(len(x[0])):
new_x = list(x).copy()
if x[0][i] == 1:
new_x[0][i] -= 1
newlist.append(new_x)
elif x[0][i] == 0:
new_x[0][i] += 1
newlist.append(new_x)
print(newlist)
最佳答案
您需要将它们转换回元组
list1 = [([1, 0, 1], 'a')]
list2 = list1.copy()
newlist = []
for x in list2:
for i in range(len(x[0])):
new_x = list(x).copy() # <- converting to the list
if x[0][i] == 1:
new_x[0][i] -= 1
newlist.append(tuple(new_x)) # <- converting to the tuple
elif x[0][i] == 0:
new_x[0][i] += 1
newlist.append(tuple(new_x)) # <- converting to the tuple
print(newlist)
关于Python - 克隆列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74106307/