python:创建重复元素的字符串列表的便捷方法

时间:2015-10-21 09:00:54

标签: python

如何创建这样的列表:

$ap | ? { $_.observability_Analysis -eq "1.00000000000000E+00" } | select -expand Offset_Angle | % { [float]$_ }

$ap | ? { $_.observability_Analysis -eq "1.00000000000000E+00" } | % { [float]$_.Offset_Angle }

如果我写["a","a","a",... (repeating "a" a hundred times") "b","b","b",(repeating "b" a hundred times.. )] ,那么我会得到["a","b"] * 100,这不是我想要的。

有没有像这个一样简单的功能,但是给了我想要的结果?

4 个答案:

答案 0 :(得分:5)

只需将乘法第一和第二个元素生成的两个列表相加:

['a']*100 + ['b']*100

它比列表理解和排序更快:

python -m timeit "sorted(['a', 'b']*100)"
100000 loops, best of 3: 9.76 usec per loop

python -m timeit "[x for x in ['a', 'b'] for y in range(100)]"
100000 loops, best of 3: 5.15 usec per loop

python -m timeit "['a']*100 + ['b']*100"
1000000 loops, best of 3: 1.86 usec per loop

答案 1 :(得分:3)

没有

localhost:8080

答案 2 :(得分:1)

sak = ['a','b','c','d']
list = sak*100
print sorted(list)
var = ['a','b']
list = sorted(var*100)

答案 3 :(得分:0)

from itertools import repeat

list(repeat('a',100)) +  list(repeat('b',100))