5

我有这个代码

a=[(1,'Rach', 'Mell', '5.11', '160'),(2, 'steve', 'Rob', '6.1', '200'), (1,'Rach', 'Mell', '5.11', '160')]

如果 id = 2,我想将姓氏 Rob 更改为 'Roberto'
所以我的想法是将元组更改为列表,以便轻松进行更改

我试过 :

a_len = len(a)
count = 0
a_list = []
while(count < a_len):
     a_list.append(a[count])
     count ++

for x, element in a_list:
     if element[0] == 2:
          a_list[x] = Roberto

但这不起作用,你们知道如何做到这一点吗?

谢谢!

4

5 回答 5

6

这样做:

a=[(1,'Rach', 'Mell', '5.11', '160'),(2, 'steve', 'Rob', '6.1', '200'), (1,'Rach', 'Mell', '5.11', '160')]

for i,e in enumerate(a):
    if e[0]==2: 
        temp=list(a[i])
        temp[2]='Roberto'
        a[i]=tuple(temp)

print a        

印刷:

[(1, 'Rach', 'Mell', '5.11', '160'), (2, 'steve', 'Roberto', '6.1', '200'), (1, 'Rach', 'Mell', '5.11', '160')]

如果你想要一个列表理解,这个:

>>> [t if t[0]!=2 else (t[0],t[1],'Roberto',t[3],t[4]) for t in a]
[(1, 'Rach', 'Mell', '5.11', '160'), (2, 'steve', 'Roberto', '6.1', '200'), (1, 'Rach', 'Mell', '5.11', '160')]
于 2013-03-07T01:57:13.937 回答
2

试试这个:

for idx, row in enumerate(a):
    id, name, surname, valA, valB = row
    if id == 2 and surname == 'Rob':
        a[idx] = (id, name, 'Roberto', valA, valB)
于 2013-03-07T01:40:59.323 回答
2

简短的回答

a_list = [(_id, first, 'Roberto' if (last == 'Rob' and _id == 2) else last, x,y) for _id, first, last, x, y in a ]

这是python的列表推导,它是python的一个很好的工具。

以上与以下代码含义相同:

a_list = []
for _id, first, last, x, y in a:

    if last == 'Rob' and _id == 2:
         last  =' Roberto'

    a_list.append((_id, first, last, x, y))
于 2013-03-07T01:42:13.160 回答
2

试试这个:

a=[(1,'Rach', 'Mell', '5.11', '160'),(2, 'steve', 'Rob', '6.1', '200'), (1,'Rach', 'Mell', '5.11', '160')]

a_list = []
for ele in a:
    a_list.append(list(ele))

for ele in a_list:

    if ele[0] == 2:
        ele[2] = "Roberto"

print a_list
于 2013-03-07T01:42:39.647 回答
1

我对 Python 不是很熟悉,但是在这里

      for x, element in a_list:
           if element[0] == 2:
           a_list[x] = Roberto

您没有从列表中选择项目。尝试

      for x in a_list:
           if x[0] == 2:
           x[3] = Roberto

X 选择列表中的元组,括号选择元组内的数据。

于 2013-03-07T01:47:23.817 回答