1

Using list comprehension I can create something simple like this

['X{}'.format(x) for x in range(2)]

which produces ['X0', 'X1']. But I want to create separate and multiple output strings, preferably from the same list comprehension statement.

I want my output to be ['X0','Y0','Z0','X1','Y1' 'Z1'] naturally something like ['X{},Y{},Z{}'.format(x,x,x) for x in range(2)], doesn't quite cut the mustard.

Any ideas of how to do this in one line?

EDIT: It is not paramount that it is on one line, but it would be nice.

0

5 Answers 5

5

Here's one way to do it using a nested comprehension:

r = ['{}{}'.format(ch, x) for x in range(2) for ch in 'XYZ']
print(r)
# ['X0', 'Y0', 'Z0', 'X1', 'Y1', 'Z1']
Sign up to request clarification or add additional context in comments.

Comments

3

Double list comprehension

reduce([ letter+str(number) for letter in 'ABC' for number in range(x)], [])

Comments

1

And one more way to go (still a one-liner):

sum([['X{}'.format(x),'Y{}'.format(x),'Z{}'.format(x)] for x in range(2)],[])
# ['X0', 'Y0', 'Z0', 'X1', 'Y1', 'Z1']

Comments

1

With a little help from itertools

In [59]: ["{}{}".format(char,i) for i,char in itertools.product(range(2), "XYZ")]
Out[59]: ['X0', 'Y0', 'Z0', 'X1', 'Y1', 'Z1']

Comments

0

Try this:

List = ['{}{}'.format(Letter, Num) for Num in range(2) for Letter in 'XYZ']
print(List)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.