连接列表中的元素 [英] Concatenate elements of a list

查看:107
本文介绍了连接列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,例如 l = ['a','b','c']
我想要一个字符串,例如'abc'。所以实际上结果是 l [0] + l [1] + l [2] ,也可以写成

I have a list like l=['a', 'b', 'c'] I want a String like 'abc'. So in fact the result is l[0]+l[1]+l[2], which can also be writte as

s = ''
for i in l:
    s += i

有什么方法可以更优雅地做到这一点?

Is there any way to do this more elegantly?

推荐答案

使用< a href = http://docs.python.org/2/library/stdtypes.html#str.join rel = noreferrer> str.join()

s = ''.join(l)

调用它的字符串用作 l 中的字符串之间的定界符:

The string on which you call this is used as the delimiter between the strings in l:

>>> l=['a', 'b', 'c']
>>> ''.join(l)
'abc'
>>> '-'.join(l)
'a-b-c'
>>> ' - spam ham and eggs - '.join(l)
'a - spam ham and eggs - b - spam ham and eggs - c'

使用 str.join()比将元素逐一串联要快很多,因为必须为每个串联创建一个新的字符串对象。 str.join()只需要创建一个一个新字符串对象。

Using str.join() is much faster than concatenating your elements one by one, as that has to create a new string object for every concatenation. str.join() only has to create one new string object.

注意 str.join()将遍历输入序列两次。一次计算输出字符串需要多大,再一次构建它。作为副作用,这意味着使用列表理解而不是生成器表达式会更快:

Note that str.join() will loop over the input sequence twice. Once to calculate how big the output string needs to be, and once again to build it. As a side-effect, that means that using a list comprehension instead of a generator expression is faster:

slower_gen_expr = ' - '.join('{}: {}'.format(key, value) for key, value in some_dict)
faster_list_comp = ' - '.join(['{}: {}'.format(key, value) for key, value in some_dict])

这篇关于连接列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆