以这种方式使用元组解包,如果您知道总是有 3 个项目:
name,type,number = i.split(',')
# now name="Adam", type="widgets", number="5769"
在您的示例中:
for triplet in sod_hng_hhl_lst:
name,type,numberString = triplet.split(",")
# because this is a string and we want a number:
num_as_integer = int(numberString)
# do something with num_as_integer
new_number = num_as_integer * 2
newtriplet = ','.join([name, type, new_number])
但是,我强烈建议使用值元组而不是拆分的字符串:
sod_hng_hhl_lst = [ ('Adam', 'widgets', 5769),
#... etc
]
这样数字保持为数字,您不必一直连接和拆分字符串。
for idx,triplet in enumerate(sod_hng_hhl_lst):
name,type,number = triplet
new_number = number * 2
# change just the number in the triplet
sod_hng_hhl_lst[idx][2] = new_number
如果人们总是有唯一的名字,那么正如 mgilson 建议的那样,您可以使用字典:
dct = {"Adam": ('widgets', 5769),
#....
}
迭代:
for person,details in dct.items():
thing, number = details
new_num = number * 2
dct[person][1] = new_num