开发者

Repeating elements in list comprehension [duplicate]

This question 开发者_C百科already has answers here: How can I get a flat result from a list comprehension instead of a nested list? (13 answers) Closed 4 months ago.

I have this list comprehension:

[[x,x] for x in range(3)]

which results in this list:

[[0, 0], [1, 1], [2, 2]]

but what I want is this list:

[0, 0, 1, 1, 2, 2]

What's the easiest to way to generate this list?


[y for x in range(3) for y in [x, x]]


>>> [i for i in range(3) for _ in range(2)]
[0, 0, 1, 1, 2, 2]


a general solution;

m = 3   #the list of integers
n = 2   # of repetitions
[x for x in range(m) for y in range(n)]


>>> [int(x/2) for x in range(6)]
[0, 0, 1, 1, 2, 2]


My solution:

def explode_list(p,n):
    arr=[]
    track=0

    if n==0:
        return arr    
    while track<len(p): 
        m=1
        while m<=n:
            arr.append(p[track])
            m=m+1
        track=track+1

    return arr


You might get away with this:

[floor(x/2) for x in range(6)]

edit1

[int(x/2) for x in range(6)]

is the more portable solution in the same vein. Although the other presented answers seem better.


[x/2 for x in range(6)]

update:

[x//2 for x in range(6)] #ok now ?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜