Python - 克隆列表

标签 python

我想克隆 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/

相关文章:

python pandas连接 'apply'的返回值时出现奇怪的错误

python - 脚本每 24 小时重新启动一次 Heroku

python - TypeError : Cannot treat the value '<function objective_rule at 0x0000000007C31D08>' as a constant because it has unknown type 'function'

python - Django:相关模型的多个实例上的filter()

python - 在 Python 中将数据库表加载到嵌套字典中

python - Anaconda-navigator 无法启动

python - Pyspark:解析一列 json 字符串

python - Pandas GroupBy 和计算 Z-Score

python多处理从多处理队列访问数据不读取所有数据

python - 在列表理解中使用列表解包来展平嵌套列表