向lis中的同一索引添加3个字符串

2024-06-16 15:14:40 发布

您现在位置:Python中文网/ 问答频道 /正文

thiswxPython教程中,我偶然发现了一种格式化列表的方法:

packages = [('jessica alba', 'pomona', '1981'), ('sigourney weaver', 'new york', '1949'),
    ('angelina jolie', 'los angeles', '1975'), ('natalie portman', 'jerusalem', '1981'),
    ('rachel weiss', 'london', '1971'), ('scarlett johansson', 'new york', '1984' )]

你如何以这样的格式添加到这个列表中? 例如:

packages.append[(item1, item2, item3)]

该列表用于将内容添加到wx.ListCtrl文件诸如此类:

for i in packages:
            index = self.list.InsertStringItem(sys.maxint, i[0])
            self.list.SetStringItem(index, 1, i[1])
            self.list.SetStringItem(index, 2, i[2])

事先谢谢你的帮助。你知道吗


Tags: 方法self列表newindexpackages教程list
1条回答
网友
1楼 · 发布于 2024-06-16 15:14:40

注:这个问题最简单的答案是

output = [(item[0],item[1],item[2]) for item.split(",") in someBigList]

其中item是逗号分隔的字符串。你知道吗

冗长的答案。

Python能够存储任何东西(是的,任何东西!)在其可移植的数据结构中。 可以在列表中存储列表,在列表中存储词典,反之亦然,可以存储对象、元组或集合。你知道吗

Tuple数据结构在Python中被广泛使用,tuplelist之间的主要区别在于,不能更改tuple内的内容,而可以在list中更改内容。不变性只是使用元组的优点之一。还有更多的优点。你知道吗

假设上面的数据是以某种形式出现的,你必须把它们都分组。 假设它们是用逗号分隔的字符串,例如在csv中。你知道吗

with open("/tmp/test.csv","r") as readFl:
    line = readFl.readlines()

lines
Out[5]: 
['jessica alba, pomona, 1981',
 'sigourney weaver, new york, 1949',
 'angelina jolie, los angeles, 1975',
 'natalie portman, jerusalem, 1981',
 'rachel weiss, london, 1971',
 'scarlett johansson, new york, 1984']

现在需要访问列表行的每个元素中的每个元素。 为此,我们使用一个元组列表。你知道吗

output = []
for line in lines:
    row = tuple(line.split(",")) # by default, split() returns a list, we cast it to a tuple.
    output.append(row)


output
Out[16]: 
[('jessica alba', 'pomona', '1981'),
 ('sigourney weaver', 'new york', '1949'),
 ('angelina jolie', 'los angeles', '1975'),
 ('natalie portman', 'jerusalem', '1981'),
 ('rachel weiss', 'london', '1971'),
 ('scarlett johansson', 'new york', '1984')]

希望这有帮助。你知道吗

相关问题 更多 >