Lists in Python - Each array in different row [duplicate] - python

This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 3 years ago.
how can I create a new list with the following format.
The 3 arrays inside each row should be in different rows.
a= [['111,0.0,1', '111,1.27,2', '111,3.47,3'],
['222,0.0,1', '222,1.27,2', '222,3.47,3'],
['33,0.0,1', '33,1.27,2', '33,3.47,3'],
['44,0.0,1', '44,1.27,2', '4,3.47,3'],
['55,0.0,1', '55,1.27,2', '55,3.47,3']]
Final desired ouput:
b=[['111,0.0,1',
'111,1.27,2',
'111,3.47,3',
'222,0.0,1',
'222,1.27,2',
'222,3.47,3',
'33,0.0,1',
'33,1.27,2',
'33,3.47,3',
'44,0.0,1',
'44,1.27,2',
'44,3.47,3',
'55,0.0,1',
'55,1.27,2',
'55,3.47,3']]

Is this what you are looking for?
b = [[j for i in a for j in i]]

To be clear, there is no concept of rows vs. columns in Python. Your end result is just a big list of str's, within another list.
You can create the big list by chaining all of the original small lists together (a[0] + a[1] + ...), for which we may use
import itertools
big_list = list(itertools.chain(*a))
To put this inside another list,
b = [big_list]

Related

Undoing list comprehension and turning it in nested for loops [duplicate]

This question already has answers here:
What does "list comprehension" and similar mean? How does it work and how can I use it?
(5 answers)
Closed 12 months ago.
Does anyone know how I can turn the following list comprehension into two nested for loops? When I try and do it I get errors.
data_list = [self.y[a][b] for a in range(side_1, side_2) for b in range(corner_1, corner_2)]
data_list = []
for a in range(side_1, side_2):
for b in range(corner_1, corner_2):
data_list.append(self.y[a][b])
If you need to iterate over every row / column index pair, you should use itertools.product() as a more concise solution than a nested for loop:
from itertools import product
result = []
for a, b in product(range(side_1, side_2), range(corner_1, corner_2)):
result.append(self.y[a][b])

Pythonic way to group a list of lists? [duplicate]

This question already has answers here:
Transpose list of lists
(14 answers)
Closed 12 months ago.
So lets say I have a hypothetical list of lists of file names in Python defined like so:
l = [["user1/stats1.csv", "user1/stats2.csv", "user1/stats3.csv"],
["user2/stats1.csv", "user2/stats2.csv", "user2/stats3.csv"]]
What would be the most pythonic way to group it by the number in statsN.csv such that the list would look like:
l = [["user1/stats1.csv", "user2/stats1.csv"],
["user1/stats2.csv", "user2/stats2.csv"],
["user1/stats3.csv", "user2/stats3.csv"],
For reference, the original list was obtained by using glob with the * wild card a la glob.glob("user1/stats*.csv") and glob.glob("user2/stats*.csv")
You could unpack the sublists and zip:
out = list(map(list, zip(*l)))
Output:
[['user1/stats1.csv', 'user2/stats1.csv'],
['user1/stats2.csv', 'user2/stats2.csv'],
['user1/stats3.csv', 'user2/stats3.csv']]
If you're using numpy, you can simply transpose:
>>> np.array(l).T.tolist()
[['user1/stats1.csv', 'user2/stats1.csv'],
['user1/stats2.csv', 'user2/stats2.csv'],
['user1/stats3.csv', 'user2/stats3.csv']]

Average entries of lists of lists [duplicate]

This question already has answers here:
How to get last items of a list in Python?
(5 answers)
Transpose list of lists
(14 answers)
Closed 1 year ago.
I have a list of lists
my_list = [[8,2,3], [8,3,6], [2,3,9], [7,3,6], [2,6,4], [8,5,8]]
and would like to take the average of the last n entries of the list for each of its entries. To clarify, here is an example:
The average of the entries of the last 3 lists of my_list is:
[(7+2+8)/3, (3+6+5)/3, (6+4+8)/3] = [5.67, 4.67, 6]
I did it with a bunch of loops of loops but I feel like there is a way to do it in probably a line or two of code. Any help is appreciated. Thanks
use np.mean after you slice your list
import numpy as np
my_list = [[8,2,3], [8,3,6], [2,3,9], [7,3,6], [2,6,4], [8,5,8]]
n = 3
np.mean(my_list[-n:], axis=0) # -> array([5.66666667, 4.66666667, 6. ])
Use a list comprehension and zip, with some help from statistics.mean to easily compute the mean:
my_list = [[8,2,3], [8,3,6], [2,3,9], [7,3,6], [2,6,4], [8,5,8]]
n = 3
from statistics import mean
[mean(x) for x in zip(*my_list[-n:])]
# OR using map
list(map(mean, zip(*my_list[-n:])))
output:
[5.666666666666667, 4.666666666666667, 6]

Transposing Lists - Python [duplicate]

This question already has answers here:
Transpose list of lists
(14 answers)
Closed 2 years ago.
I have list a = [[1,2,3],[4,5,6],[7,8,9]] and want to convert that into list b = [[1,4,7],[2,5,8],[3,6,9]]. Is it possible to do that?
i.e. take all the value in the first element spot and combine into a new list, same for 2nd, 3rd etc...
Assume the initial list has an unknown amount of elements and each element has unknown length, i.e. there could be 40 elements in a and each element contains 14 numbers. Thanks
There are a couple of ways to do it.
The first one is as follows:
print(list(map(list, zip(*a))))
another option is using numpy as follows:
print(np.array(a).T.tolist())
Another option is to use list comprehension as follows:
print([[row[i] for row in a] for i in range(len(a[0]))])
Using numpy you can try this
import numpy as np
a= [[1,2,3],[4,5,6],[7,8,9]]
ar = np.array(a)
a_transpose = at.T.tolist()

how to concatenate two lists objects and join string objects in list [duplicate]

This question already has answers here:
How to join two strings from different tuples but in the same index using Python?
(4 answers)
Closed 4 years ago.
How do I concatenate two lists in Python?
example:
input:
x=['saeed']
y=['gharif']
output expected:
z=['saeedgharif']
You have two lists, each with a single element, so you can make a new list by concatenating the [0] element of each list
>>> z = [x[0] + y[0]]
>>> z
['saeedgharif']
Using zip and a list comprehension.
Ex:
x=['saeed']
y=['gharif']
print( [i+v for i,v in zip(x, y)] )
Output:
['saeedgharif']
Join is way more readable, and just use + to combine both lists.
x=['saeed']
y=['gharif']
z=''.join(x+y)

Categories