This question already has answers here:
Transpose list of lists
(14 answers)
Closed last month.
I have a list of 4 list show below.
list1 = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l']]
How do I create a list of list by element position so that the new list of list is as follows?
list2 = [['a', 'd', 'g', 'j'], ['b', 'e', 'h', 'k'], ['c', 'f', 'i', 'l']]
I tried using a for loop such as
res = []
for listing in list1:
for i in list:
res.append(i)
however it just created a single list.
Use zip with the * operator to zip all of the sublists together. The resulting tuples will have the list contents you want, so just use list() to convert them into lists.
>>> list1 = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l']]
>>> [list(z) for z in zip(*list1)]
[['a', 'd', 'g', 'j'], ['b', 'e', 'h', 'k'], ['c', 'f', 'i', 'l']]
Related
I have some extremely large lists of character strings I need to parse. I need to break them into smaller lists based on a pre-defined character string, and I figured out a way to do it, but I worry that this will not be performant on my real data. Is there a better way to do this?
My goal is to turn this list:
['a', 'b', 'string_to_split_on', 'c', 'd', 'e', 'f', 'g', 'string_to_split_on', 'h', 'i', 'j', 'k', 'string_to_split_on']
Into this list:
[['a', 'b'], ['c', 'd', 'e', 'f', 'g'], ['h', 'i', 'j', 'k']]
What I tried:
# List that replicates my data. `string_to_split_on` is a fixed character string I want to break my list up on
my_list = ['a', 'b', 'string_to_split_on', 'c', 'd', 'e', 'f', 'g', 'string_to_split_on', 'h', 'i', 'j', 'k', 'string_to_split_on']
# Inspect List
print(my_list)
# Create empty lists to store dat ain
new_list = []
good_letters = []
# Iterate over each string in the list
for i in my_list:
# If the string is the seporator, append data to new_list, reset `good_letters` and move to the next string
if i == 'string_to_split_on':
new_list.append(good_letters)
good_letters = []
continue
# Append letter to the list of good letters
else:
good_letters.append(i)
# I just like printing things thay because its easy to read
for item in new_list:
print(item)
print('-'*100)
### Output
['a', 'b', 'string_to_split_on', 'c', 'd', 'e', 'f', 'g', 'string_to_split_on', 'h', 'i', 'j', 'k', 'string_to_split_on']
['a', 'b']
----------------------------------------------------------------------------------------------------
['c', 'd', 'e', 'f', 'g']
----------------------------------------------------------------------------------------------------
['h', 'i', 'j', 'k']
----------------------------------------------------------------------------------------------------
You can also use one line of code:
original_list = ['a', 'b', 'string_to_split_on', 'c', 'd', 'e', 'f', 'g', 'string_to_split_on', 'h', 'i', 'j', 'k', 'string_to_split_on']
split_string = 'string_to_split_on'
new_list = [sublist.split() for sublist in ' '.join(original_list).split(split_string) if sublist]
print(new_list)
This approach is more efficient when dealing with large data set:
import itertools
new_list = [list(j) for k, j in itertools.groupby(original_list, lambda x: x != split_string) if k]
print(new_list)
[['a', 'b'], ['c', 'd', 'e', 'f', 'g'], ['h', 'i', 'j', 'k']]
This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 4 years ago.
I am currently writing a program but came across an error in the code. I got it down to this:
This is the basis of the problem:
original_list = ["a","b","c","d","e","f","g","h","i","j"]
value = "a"
new_list = original_list
print(original_list)
new_list.pop(new_list.index(value))
print(original_list)
print(new_list)
I would expect this to output:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
But instead it gives this, where the value "a" has been removed from the original list:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
I cannot seem to figure out why, does anyone know?
When you write new_list = original_list, you are just making another name for the same old list.
If you want to really create a new list, you need to clone the old one. One way is to use new_list = list(original_list). The best way depends on the contents of the list.
This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 6 years ago.
I am using a recursive function on a list of lists with an accumulator, but instead of creating the right list of lists, it makes a list with duplicates of the last item inserted in the accumulator. I recreated the problem in a much simpler recursive function and list. This function takes a list of lists and makes 2 copies and reverses them n times.
def recursauto(x, n, instSet):
#Base Case
if(n==0):
instSet.append(x)
print(x) #Print to see what SHOULD be added
else:
temp = [x]*(2) # Make a list with 2 copies of the original list
for i in range(len(temp)):
temp[i][i] = temp[i][i][::-1] # Make the list backwards
for i in range(2):
recursauto(temp[i], n-1, instSet) #Input each element
MyList = [] #Empyt list for accumulator
print("Correct output:")
recursauto([["A", "l", "e", "x"], ["A", "b", "d", "a", "l", "a", "h"]], 2, MyList)
print("Wrong printed list:")
for i in MyList:
print(i) #Print what is in the accumulator
The output comes out wrong and the accumulator does not have the right things that were put into it.
Correct output:
[['A', 'l', 'e', 'x'], ['A', 'b', 'd', 'a', 'l', 'a', 'h']]
[['A', 'l', 'e', 'x'], ['A', 'b', 'd', 'a', 'l', 'a', 'h']]
[['x', 'e', 'l', 'A'], ['h', 'a', 'l', 'a', 'd', 'b', 'A']]
[['x', 'e', 'l', 'A'], ['h', 'a', 'l', 'a', 'd', 'b', 'A']]
Wrong printed list:
[['x', 'e', 'l', 'A'], ['h', 'a', 'l', 'a', 'd', 'b', 'A']]
[['x', 'e', 'l', 'A'], ['h', 'a', 'l', 'a', 'd', 'b', 'A']]
[['x', 'e', 'l', 'A'], ['h', 'a', 'l', 'a', 'd', 'b', 'A']]
[['x', 'e', 'l', 'A'], ['h', 'a', 'l', 'a', 'd', 'b', 'A']]
I know that there is an easier way to do this, but the function I'm actually making requires recursion. Like I said, this is just a simplified recreation of the problem I am having.
temp = [x]*(2)
The above line does not create a list of two copies of the original list; in fact, it just stores a reference to the same original list twice. If you want a distinct copy of x, try using the list copy constructor like temp = [list(x), list(x)] or alternatively the shallow copy method [x.copy() x.copy()].
See the below example.
>>> ls = ['a']
>>> dup = [ls] * 2
>>> dup
[['a'], ['a']]
>>> ls.append('b')
>>> dup
[['a', 'b'], ['a', 'b']]
I have to merge nested lists which have an overlap. I keep thinking that there has to be an intelligent solution using list comprehensions and probably difflib, but I can't figure out how it should work.
My lists look like this:
[['C', 'x', 'F'], ['A', 'D', 'E']]
and
[['x', 'F', 'G', 'x'], ['D', 'E', 'H', 'J']].
They are above another, like rows in a matrix. Therefore, they have overlap (in the form of
[['x', 'F'], ['D', 'E']]).
A merge should yield:
[['C', 'x', 'F', 'G', 'x'], ['A', 'D', 'E', 'H', 'J']].
How can I achieve this?
You can try something like this.
list1 = [['C', 'x', 'F'], ['A', 'D', 'E']]
list2 = [['x', 'F', 'G', 'x'], ['D', 'E', 'H', 'J']]
for x in range(len(list1)):
for element in list2[x]:
if element not in list1[x]:
list1[x].append(element)
print list1[x]
Output:
['C', 'x', 'F', 'G']
['A', 'D', 'E', 'H', 'J']
I hope this helps you.
This question already has answers here:
Sorting Python list based on the length of the string
(7 answers)
Closed 7 years ago.
I have the following list
a = [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h'], ['i', 'j', 'k', 'l'], ['m', 'n'], ['o']]
I would like to sort the list based on the length of their sub lists.
The result should be like:
a = [['o'],['d','e'],['m', 'n'],['a', 'b', 'c'],['f', 'g', 'h'], ['i','j','k','l']]
Use key parameter available in sort and sorted. It specifies a function of one argument that is used to extract a comparison key from each list element
In [6]: a = [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h'], ['i', 'j', 'k', 'l'], ['m', 'n'], ['o']]
In [7]: a.sort(key=len)
In [8]: print a
[['o'], ['d', 'e'], ['m', 'n'], ['a', 'b', 'c'], ['f', 'g', 'h'], ['i', 'j', 'k', 'l']]
can be done by
sorted(a, key=len)