简体   繁体   中英

List comprehension for multiplying each string in a list by numbers from given range

I am trying out the list comprehensions. But I got stuck when I tried to write a list comprehension for the following code.

a = ['x','y','z']
result = []
for i in a:
    for j in range(1,5):
        s = ''
        for k in range(j):
            s = s + i
        result.append(s)
result

output for this is:

['x', 'xx', 'xxx', 'xxxx', 'y', 'yy', 'yyy', 'yyyy', 'z', 'zz', 'zzz', 'zzzz']

Is it even possible to write a list comprehension for this code? if it is how would you write it?

Here it is:

[ x * i for x in ['x','y','z'] for i in range(1,5)  ]

The result:

['x', 'xx', 'xxx', 'xxxx', 'y', 'yy', 'yyy', 'yyyy', 'z', 'zz', 'zzz', 'zzzz']
a = ['x','y','z']
result = []
result+=[i*j for i in a for j in range(1,5)]
result

This will work

Possible!!!!

>>> a = ['x','y','z']
>>> sorted([i*j for j in range(1,5) for i in a])
['x', 'xx', 'xxx', 'xxxx', 'y', 'yy', 'yyy', 'yyyy', 'z', 'zz', 'zzz', 'zzzz']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM