Python:替换转换为列表的元组中的项

Python:替换转换为列表的元组中的项,python,list,tuples,Python,List,Tuples,最近出现了一个奇怪的问题。我正在尝试更改已转换为列表的元组中的一项 但是我所拥有的 paths = [(1,2),(2,3),(2,0)] plist = [] for pathlist in paths: for n in range(0, len(pathlist)): if pathlist[n] == 2: plist = list(pathlist) plist[n] = 4 pathli

最近出现了一个奇怪的问题。我正在尝试更改已转换为列表的元组中的一项

但是我所拥有的

paths = [(1,2),(2,3),(2,0)]
plist = []

for pathlist in paths:
    for n in range(0, len(pathlist)):
        if pathlist[n] == 2:
            plist = list(pathlist)
            plist[n] = 4
            pathlist = tuple(plist)
            print(pathlist)
print(paths)

实际上没有更改列表
路径
中的值,即它与最初的值保持不变,即使我可以从
打印(路径列表)
判断它已正确修改。我不能删除它并附加它,因为这会抵消for循环。谢谢你们的帮助,伙计们

路径列表变量是一个新实例,它不会影响路径列表成员

试试这个:

for i in range(len(paths)):
    pathlist = paths[i]
    for n in range(0, len(pathlist)):
        if pathlist[n] == 2:
            plist = list(pathlist)
            plist[n] = 4
            paths[i] = tuple(plist)
            print(paths[i])

您只需更改所修改的列表副本。您没有直接修改
路径

这样做:

>>> for i, pl in enumerate(paths):
    for j, n in enumerate(pl):
        if n==2:
            pl = list(pl)
            pl[j] = 4
            paths[i] = pl


>>> paths
[[1, 4], [4, 3], [4, 0]]

你应该在每个回合中把路径列表附加到一些列表中…试试这个

paths = [(1,2),(2,3),(2,0)]
flist = []
for pathlist in paths:
    for n in range(0, len(pathlist)):
        if pathlist[n] == 2:
            plist = list(pathlist)
            plist[n] = 4
            pathlist = tuple(plist)
            flist.append(pathlist)
print(flist)
输出将是

[(1, 4), (4, 3), (4, 0)]

虽然最初
pathlist
指向
path
的元素,但在循环中重新分配该链接时,该链接将丢失

for pathlist in paths:
    ...
    pathlist = 'new value'
用一列整数试试这个更简单的例子<代码>列表未更改

alist = [1,2,3]
for x in alist:
    x = x*2
但是,如果元素是列表,则可以在不丢失到
alist
的链接的情况下更改它们

alist = [[1],[2],[3]]
for x in alist:
    x[0] = x[0]*2

不幸的是,出于这些目的,元组更像是整数而不是列表。您必须使用索引来修改列表[i],或者按照列表理解答案重建列表。

您在这里的目的是什么?我不确定我是否理解您所期望的
路径
是什么。。。