'how to zip strings 2x3 in python
arr = ["zx", "wu", "tr"] # new array should be [ 'zwt', 'xur']
for i in range(len(nums)):
t = ''
word = nums[i]
for j in range(len(word)):
t += nums[j][i]
print(t)
zx
wu
tr
should create new array
zwt
xur
This code above works only if len of each str is 3 and total num of strings is 3 - ['abc', 'cde', 'ghi']
In case there is string of len 2 it's not working. HOw to transpose/zip it?
Solution 1:[1]
Use the builtin zip function, which takes any number of iterables as an argument and returns a single iterable that gives you tuples of one item from each.
If you pass each element of arr to zip as an argument, you get:
>>> arr = ["zx", "wu", "tr"]
>>> list(zip(arr[0], arr[1], arr[2]))
[('z', 'w', 't'), ('x', 'u', 'r')]
Of course, you don't want to have to enumerate each element of arr in your code -- that's what the * (spread) operator is for:
>>> list(zip(*arr))
[('z', 'w', 't'), ('x', 'u', 'r')]
Since zip gives you tuples, you then want to use str.join to turn those tuples into strings:
>>> [''.join(t) for t in zip(*arr)]
['zwt', 'xur']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Samwise |
