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?
This has probably been asked before, please read the language's docs at docs.python.org and consider using a simple "for i in range" loop where you can c += [a[i]] * b[i] in each iteration. A better duplicate target: Repeat each item in a list a number of times specified in another list.
List comprehension works with string lists also. The following creates a new list of strings that contains 'a'. Above, the expression if 'a' in s returns True if an element contains a character 'a'.
Use a list comprehension to multiply each number in a range by specific number, e.g. result = [num * 2 for num in range(1, 6)] . The list comprehension iterates over the range and uses the multiplication * operator to multiply the current number by another number.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With