Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何复制列表中的字符串?_Python_String_List - Fatal编程技术网

Python 如何复制列表中的字符串?

Python 如何复制列表中的字符串?,python,string,list,Python,String,List,我有一张单子 list1=['a','b','c] 我想复制列表中的每个字符串 像这样 list2=['a','a','b','b','c','c'] 但是当我使用这个代码时 list2=[x*2 for x in list1] 我明白了 如何更改代码以实现结果?我将使用itertools.chain和itertools.repeat: from itertools import chain, repeat chars = ['a', 'b', 'c'] repeat_count = 3

我有一张单子

list1=['a','b','c]
我想复制列表中的每个字符串

像这样

list2=['a','a','b','b','c','c']
但是当我使用这个代码时

list2=[x*2 for x in list1]
我明白了


如何更改代码以实现结果?

我将使用
itertools.chain
itertools.repeat

from itertools import chain, repeat

chars = ['a', 'b', 'c']
repeat_count = 3

list(chain.from_iterable(repeat(char, repeat_count) for char in chars))
输出:

['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']

我会使用
itertools.chain
itertools.repeat

from itertools import chain, repeat

chars = ['a', 'b', 'c']
repeat_count = 3

list(chain.from_iterable(repeat(char, repeat_count) for char in chars))
输出:

['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']

如果不使用itertools,这可以通过下面的嵌套列表理解来完成

list1=['a','b','c']

print([y for x in list1 for y in [x]*2])
# ['a', 'a', 'b', 'b', 'c', 'c']

print([y for x in list1 for y in [x]*3])
# ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']

如果不使用itertools,这可以通过下面的嵌套列表理解来完成

list1=['a','b','c']

print([y for x in list1 for y in [x]*2])
# ['a', 'a', 'b', 'b', 'c', 'c']

print([y for x in list1 for y in [x]*3])
# ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']

您可以使用第二个
for
循环和函数
range()


您可以使用第二个
for
循环和函数
range()


这是一个很好的答案。