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.
Related
This question already has answers here:
Difference between list += ‘string’ and list +=[‘string’]
(2 answers)
Python append() vs. + operator on lists, why do these give different results?
(7 answers)
Closed last month.
import random
a=['sai','raju','phani']
b=[]
for I in a:
b += random.Choice(a)
print(b)
result:
['s', 'a', 'i', 's', 'a', 'i', 'r', 'a', 'j', 'u']
but expected to be total string not individual
['sai','sai','raju']
What did I do wrong?
You can use random.choices and pass in the number of samples for b in the argument k.
import random
a=['sai','raju','phani']
b=[]
b = random.choices(a, k=len(a))
print(b)
EDIT: if you want it in a for loop:
for i in range(len(a)):
b.append(random.choice(a))
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:
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'
I have two sequences of strings A and B input as lists which may or may not have contiguous duplicates.
A = ['S','D','D','M','C','M']
B = ['D','D','S','C','C','M']
I want to merge them while minimizing contiguous duplicates while maintaining the order of each sequence A and B.
R = ['D','S','D','S','D','C','D','M','C','M','C','M']
I want to find a dynamic programming approach to solve this problem but I am not sure where to begin or how to do it in python.
I'm not sure how your merging us supposed to work. I tried
[k for k, v in itertools.groupby(heapq.merge(A, B))]
But that gives me:
['D', 'S', 'D', 'M', 'C', 'M', 'S', 'C', 'M']
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python - Intersection of two lists
i'm trying to compare two lists in order to find the number of elements they have in common.
The main problem I'm having is when either list contains repeated elements, for example
A = [1,1,1,1] and
B = [1,1,2,3]
using the code
n = 0
for x in A:
if x in B:
n += 1
print n
gives me the output that n = 4, as technically all elements of A are in B
I'd like to get the output that n = 2, preferably without using sets, Is there anyway I can adapt my code, or a new way of thinking about the problem to achieve this?
Thanks
It's not entirely clear what your specification is, but if you want the number of elements in A that appear in B, without regard to order, but with regard to multiplicity, use collections.Counter:
>>> from collections import Counter
>>> A = [1,1,1,1]
>>> B = [1,1,2,3]
>>> C = Counter(A) & Counter(B)
>>> sum(C.itervalues())
2
>>> list(C.elements())
[1, 1]
Here is an efficient (O(n logn)) way to do it without using sets:
def count_common(a, b):
ret = 0
a = sorted(a)
b = sorted(b)
i = j = 0
while i < len(a) and j < len(b):
c = cmp(a[i], b[j])
if c == 0:
ret += 1
if c <= 0:
i += 1
if c >= 0:
j += 1
return ret
print count_common([1,1,1,1], [1,1,2,3])
If your lists are always sorted, as they are in your example, you can drop the two sorted() calls. This would give an O(n) algorithm.
Here's an entirely different way of thinking about the problem.
Imagine I've got two words, "hello" and "world". To find the common elements, I could iterate through "hello", giving me ['h', 'e', 'l', 'l', 'o']. For each element in the list, I'm going to remove it from the second list(word).
Is 'h' in ['w', 'o', 'r', 'l', 'd']? No.
Is 'e' in ['w', 'o', 'r', 'l', 'd']? No.
Is 'l' in ['w', 'o', 'r', 'l', 'd']? Yes!
Remove it from "world", giving me ['w', 'o', 'r', 'd'].
is 'l' in ['w', 'o', 'r', 'd']? No.
Is 'o' in ['w', 'o', 'r', 'd']?
Yes! Remove it ['w', 'o', 'r', 'd'], giving me ['w', 'r', 'd']
Compare the length of the original object (make sure you've kept a copy around) to the newly generated object and you will see a difference of 2, indicating 2 common letters.
So you want the program to check whether only elements at the same indices in the two lists are equal? That would be pretty simple: Just iterate over the length of the two arrays (which I presume, are supposed to be of the same length), say using a variable i, and compare each by the A.index(i) and B.index(i) functions.
If you'd like, I could post the code.
If this is not what you want to do, please do make your problem clearer.