This question already has answers here:
Transpose list of lists
(14 answers)
Closed 3 years ago.
I have an array like this:
arr = [['a', 'b', 'c', 'd'],
['e', 'f', 'g', 'h'],
['i', 'j']]
How to get the output like this?
str = aei bfj cg dh
So basically, how to print a jagged array vertically?
from itertools import zip_longest
for row in zip_longest(*arr, fillvalue=''):
print(' '.join(row))
You can use itertools.zip_longest to stride column-wise, and then filter out when None is encountered. Then pass that as a generator expression through str.join to create a single space-delimited string.
>>> import itertools
>>> ' '.join(''.join(filter(None, i)) for i in itertools.zip_longest(*arr))
'aei bfj cg dh'
Related
This question already has an answer here:
Extract the first letter from each string in a numpy array
(1 answer)
Closed 2 years ago.
So I have a large array shaped like (n, m) filled with strings. A small example would be:
string_array = np.array([
['hello', 'world'],
['greetings', 'all'],
['merry', 'christmas']
])
I'd like all the first characters of each string, but for some reason I'm having struggles. My first guess would have been to use:
>>> string_array[:, :][0]
Which did not work, because I just take the first row out of my matrix. I want the result that you get when you use
>>> string_array[0, 0][0]
>>> 'h'
But now for every element in my array? I'd love a solution without loops of course. Just for clarity, I want the following:
array([
['h', 'w'],
['g', 'a'],
['m', 'c']
])
You could use np.vectorize
>>> np.vectorize(lambda s: s[0])(string_array)
array([['h', 'w'],
['g', 'a'],
['m', 'c']], dtype='<U1')
Though please note that np.vectorize doesn't actually "vectorize" it applies a function over an array in a loop.
Edit: Looks like this question has already been asked and there is a nice performance analysis of other approaches.
This question already has answers here:
How do I find the duplicates in a list and create another list with them?
(42 answers)
Closed 3 years ago.
I have a list with several stings, with some being duplicates. I need to pull out all the duplicate strings and append them into a new list. How can I do that?
list_i = ['a','b','a','c','a','c','g','w','s','c','d','a','b','c','a','e']
Use an OrderedDict to get a list without the duplicates then remove those from a copy of the original
from collections import OrderedDict
list_i = ['a','b','a','c','a','c','g','w','s','c','d','a','b','c','a','e']
non_dupes = list(OrderedDict.fromkeys(list_i))
dupes = list(list_i)
for d in non_dupes:
dupes.remove(d)
print(dupes)
#['a', 'a', 'c', 'c', 'a', 'b', 'c', 'a']
print(non_dupes)
#['a', 'b', 'c', 'g', 'w', 's', 'd', 'e']
This question already has answers here:
Matrix Transpose in Python [duplicate]
(19 answers)
How do I transpose a List? [duplicate]
(4 answers)
Closed 4 years ago.
I have a list with lists in it.
[['H','J','K','L'],['Q','W','E','R'],['R','W','Q','T']]
I want to print the same indexes within one line with a space between them.the So output would be:
H Q R
J W W
K E Q
L R T
I tried using for loop using enumerate and while loop. Nothing seems to work and I'm just a beginner so I don't even know the correct way to approach this. I'd be really grateful if someone could help me out.
Thanks a lot! Have a nice day!
You can use str.join with zip:
s = [['H', 'J', 'K', 'L'], ['Q', 'W', 'E', 'R'], ['R', 'W', 'Q', 'T']]
new_s = '\n'.join(' '.join(i) for i in zip(*s))
Output:
H Q R
J W W
K E Q
L R T
'''
OP has 3 nested lists. OP wants to print each row of the list unto a line with
a space in between each line item.
'''
sample_list = [['H', 'J', 'K', 'L'], ['Q', 'W', 'E', 'R'], ['R', 'W', 'Q', 'T']]
import numpy as np
sample_array = np.array(sample_list)
print(sample_array.reshape(4, 3))
Here is the output:
[['H' 'J' 'K']
['L' 'Q' 'W']
['E' 'R' 'R']
['W' 'Q' 'T']]
As a beginner, it may be useful to learn about numpy. It simplifies tasks such as this when you are working with data in lists. What I did here is I created a numpy array from the nested list that you showed. numpy has a method called. reshape() that allows you to align the amount of rows and columns that you want for the data. In your example you wanted 4 rows and 3 columns for the letter, so passing 4, 3 to the .reshape() function will allow you to get 4 rows and 3 columns for the data. As a beginner, there are libraries in Python such as numpy that can help you simplify tasks such as this. I hope that this answer helps as you learn more.
For your specific case it's sufficient to do the following:
for i in range(len(list_a[0])):
print(" ".join([l[i] for l in list_a]))
The for loop makes sure that you are getting element in the order you want and the list comprehension just gets elements from sublists at specified index and prints them in order.
This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 8 years ago.
I have a list in python that looks like that: [a,b,c,d,e,f,g,h,i]. I would like to convert this list to a list of lists (nested list). The second level of lists should contain four elements maximal. Therefore, the new list should look like that:
[
[a,b,c,d],
[e,f,g,h],
[i],
]
Is there a pythonic way to do this? I will have to do this several times so I would be pleased if anybody knows a way of doing this without using hundreds of indexes.
You can use a list comprehension, xrange, and Explain Python's slice notation:
>>> lst = ['a', 'b', 'c', 'd', 'e',' f', 'g',' h', 'i']
>>> n = 4 # Size of sublists
>>> [lst[x:x+n] for x in xrange(0, len(lst), n)]
[['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i']]
>>>
This question already has answers here:
Flatten an irregular (arbitrarily nested) list of lists
(51 answers)
Closed 10 years ago.
I want convert list as follow:
list=[['a','b','c','d'],'e','f']
to
list['a','b','c','d','e','f']
how could I do this....Helples..
Check out itertools.chain, I think it's exactly what you need: http://docs.python.org/2/library/itertools.html#itertools.chain
>>> import itertools as it
>>> li = [['e', 'f', 'g'], 'a', 'b']
>>> list(it.chain.from_iterable(li))
['e', 'f', 'g', 'a', 'b']
This is pretty much the example from the documentation of that function, which is always a good place to start...