I have a python list ['a1', 'b1', 'a2', 'b2','a3', 'b3']
. Set m=3
and I want get this list using loops, because here m=3
could be a larger number such as m=100
.
Since we can have
m = 3
['a' str(i) for i in np.arange(1,m 1)]
# ['a1', 'a2', 'a3']
['b' str(i) for i in np.arange(1,m 1)]
# ['b1', 'b2', 'b3']
then I try to get ['a1', 'b1', 'a2', 'b2','a3', 'b3']
using
[ ['a','b'] str(i) for i in np.arange(1,m 1)]
and have TypeError: can only concatenate list (not "str") to list
Then I try
[ np.array(['a','b']) str(i) for i in np.arange(1,m 1)]
and I still get errors as UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U1'), dtype('<U1')) -> None
.
How can I fix the problem? And even more, how to get something like ['a1', 'b1', 'c1', 'a2', 'b2','c2','a3', 'b3', 'c3']
through similar ways?
CodePudding user response:
You can have more than one for
in a list comprehension:
prefixes = ['a', 'b', 'c']
m = 3
output = [f"{prefix}{num}" for num in range(1, m 1) for prefix in prefixes]
print(output) # ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'a3', 'b3', 'c3']
If you have multiple for
s, those will be nested, as in
for num in range(1, m 1):
for prefix in prefixes:
...
CodePudding user response:
You could use itertools.product
to get all combinations of the the letters and the m
range and then join them in an f-string (rather than using join
as one element is an integer so would require converting to a string):
[f'{t[1]}{t[0]}' for t in itertools.product(range(1, m 1), ['a', 'b'])]
Output:
['a1', 'b1', 'a2', 'b2', 'a3', 'b3']
CodePudding user response:
You need to iterate on both the range of numbers and the list of strings
In [106]: [s str(i) for i in range(1,4) for s in ['a','b']]
Out[106]: ['a1', 'b1', 'a2', 'b2', 'a3', 'b3']