Reputation: 305
In Python, I have this list:
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
and I want to convert it into a list of strings, like:
['000', '001', '010', '011', '100', '101', '110', '111']
This was my attempt:
val = [0,1]
['{x}{y}{z}'.format(x=x,y=y,z=z) for x in val for y in val for z in val]
But in some cases, the length of the string e.g.'001' may be variable (e.g. '01101') so it is frustrating editing this part '{x}{y}{z}'.format(x=x,y=y,z=z)
each time
How can I do that?
Upvotes: 2
Views: 92
Reputation: 1148
Here's the more simplifier version
a=[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
b=[]
for i in a:
c=str(i)
c=c.replace("(","")
c=c.replace(")","")
c=c.replace(",","")
b.append(c)
print(b) # ['0 0 0', '0 0 1', '0 1 0', '0 1 1', '1 0 0', '1 0 1', '1 1 0', '1 1 1']
or in just one line:
b=[str(i).replace("(","").replace(")","").replace(",","") for i in a]
print(b) #['0 0 0', '0 0 1', '0 1 0', '0 1 1', '1 0 0', '1 0 1', '1 1 0', '1 1 1']
Upvotes: 2
Reputation: 2660
Using for loops and concatenation:
arr1 = [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
arr2 = []
for ind in range(len(arr1)):
arr2.append("")
for n in arr1[ind]:
arr2[ind] += str(n)
print(arr2)
While this is a very simple and readable approach, there are other ways to do this that take up less space and have slightly more complex implementations, such as @Olvin Roght's solution.
Upvotes: 1