把str连接到list的好方法?

2024-06-17 09:59:14 发布

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

有没有办法有效地连接str和list?

inside = [] #a list of Items

class Backpack:
    def add(toadd):
        inside += toadd

print "Your backpack contains: " #now what do I do here?

Tags: ofaddyourdefitemsdolistclass
2条回答

你可以试试这个:

In [4]: s = 'Your backpack contains '

In [5]: l = ['item1', 'item2', 'item3']

In [6]: print s + ', '.join(l)
Your backpack contains item1, item2, item3

与设置中的其他Python方法相比,join方法有点奇怪,但在本例中,它的意思是“获取此列表并将其转换为字符串,用逗号和空格将元素连接在一起”。这有点奇怪,因为您指定了要首先与之连接的字符串,这有点不寻常,但很快就会成为第二种性质:)有关讨论,请参见here

如果要将项添加到inside(列表),则将项添加到列表的主要方法是使用append方法。然后使用join将所有项作为字符串组合在一起:

In [11]: inside = []

In [12]: inside.append('item1')

In [13]: inside.append('item2')

In [14]: inside.append('item3')

In [15]: print 'Your backpack contains ' + ', '.join(inside)
Your backpack contains item1, item2, item3

听起来你只是想在字符串列表中添加一个字符串。那只是append

>>> inside = ['thing', 'other thing']
>>> inside.append('another thing')
>>> inside
['thing', 'other thing', 'another thing']

这里没有特定于字符串的内容;同样的内容也适用于Item实例列表、字符串列表或37种不同类型37种不同事物的列表。

一般来说,append是将单个事物连接到列表末尾的最有效方法。如果您想要连接一堆东西,并且已经将它们放在一个列表(或迭代器或其他序列)中,则不要一次一个地执行它们,而是使用extend一次执行所有操作,或者使用+=代替(这意味着与列表的extend相同):

>>> inside = ['thing', 'other thing']
>>> in_hand = ['sword', 'lamp']
>>> inside += in_hand
>>> inside
['thing', 'other thing', 'sword', 'lamp']

如果以后要将该字符串列表连接到单个字符串中,那就是join方法,RocketDonkey解释道:

>>> ', '.join(inside)
'thing, other thing, another thing'

我猜你想变得更花哨一点,在最后一项之间加一个“and”,如果少于三个就跳过逗号,等等。但是如果你知道如何分割列表和如何使用join,我想这可以留给读者作为练习。

如果您尝试从另一个方向将列表连接到字符串,则需要以某种方式将该列表转换为字符串。您可以只使用str,但通常这并不能满足您的需要,您将需要上面的join示例。

不管怎样,一旦有了字符串,就可以将其添加到另一个字符串中:

>>> 'Inside = ' + str(inside)
"Inside = ['thing', 'other thing', 'sword', 'lamp']"
>>> 'Inside = ' + ', '.join(inside)
'Inside = thing, other thing, another thing'

如果您有一个不是字符串的内容列表,并且希望将它们添加到字符串中,则必须决定这些内容的适当字符串表示形式(除非您对repr满意):

>>> class Item(object):
...   def __init__(self, desc):
...     self.desc = desc
...   def __repr__(self):
...     return 'Item(' + repr(self.desc) + ')'
...   def __repr__(self):
...     return self.desc
...
>>> inside = [Item('thing'), Item('other thing')]
>>> 'Inside = ' + repr(inside)
... "Inside = [Item('thing'), Item('other thing')]"
>>> 'Inside = ' + str(inside)
... "Inside = [Item('thing'), Item('other thing')]"
>>> 'Inside = ' + ', '.join(str(i) for i in inside)
... 'Inside = thing, other thing'

注意,只要在一个Items列表中调用str就可以调用单个项上的repr;如果要调用它们上的str,就必须显式地执行;这就是str(i) for i in inside部分的作用。

总而言之:

class Backpack:
    def __init__(self):
        self.inside = []
    def add(self, toadd):
        self.inside.append(toadd)
    def addmany(self, listtoadd):
        self.inside += listtoadd
    def __str__(self):
        return ', '.join(str(i) for i in self.inside)

pack = Backpack()
pack.add('thing')
pack.add('other thing')
pack.add('another thing')
print 'Your backpack contains:', pack

运行此命令时,它将打印:

Your backpack contains: thing, other thing, another thing

相关问题 更多 >