[英]How do I sum the first value in each tuple in a list of tuples in Python?
[英]How do I modify the first value in each list / tuple in python?
我有一個列表/元組列表,例如:
objects = [
(1, "a", "foo"), # or I can make [1, "a", "foo"] instead
(20, "bb", "bar"),
(1231, "cde", "foo2"),
]
現在我想修改每個元組的第一個值(例如,做一個簡單的to_string
轉換):
objects = [
("1", "a", "foo"), # or I can make [1, "a", "foo"] instead
("20", "bb", "bar"),
("1231", "cde", "foo2"),
]
目前我創建了一個全新的列表:
objects_str = []
for object in objects:
objects_str.append((str(object[0]), object[1], object[2]))
有更清潔的方法嗎? 我想過使用namedtuple
但看起來它們也是不可變的。 另一種選擇可能是使用:
objects_str = []
for object in objects:
object[0] = str(object[0])
objects_str.append(object)
注意:我也允許改變原始對象。
您可以使用enumerate
來迭代objects
以使用索引就地修改它:
for i, (first, *rest) in enumerate(objects):
objects[i] = str(first), *rest
objects
變成:
[('1', 'a', 'foo'), ('20', 'bb', 'bar'), ('1231', 'cde', 'foo2')]
只需修改列表:
for i, object in enumerate(objects):
objects[i] = (str(object[0]), object[1], object[2])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.