This question already has answers here:
Iterate over all lists inside a list of varied lengths [closed]
(3 answers)
How does one merge a list, but maintain the previous lists order?
(3 answers)
Closed 2 years ago.
I want to do something called lacing.
I have 2 lists:
list1 = ['4,5', '5,3', '1,2', '0,4', '6,2']
list2 = ['1,3', '6,4', '8,8']
I want my output to look like this
list3 = ['4,5','1,3','5,3','6,4','1,2','8,8','0,4', '6,2']
So the new list should have the first element of the first list, then the first element of the second list followed by the second element of the first list, then the second element in the second list.
Finally, if they are not equal, I would like to dump the rest at the end of the new list.
I tried using
for l1,l2 in zip(one_final,three_final):
list3.append(l1+l2)
but I got this back
['4,50,6', '5,33,1', '1,27,8', '0,46,6', '6,27,7']
How can I do this?
Thank you.
Given:
list1 = ['4,5', '5,3', '1,2', '0,4', '6,2']
list2 = ['1,3', '6,4', '8,8']
You can do:
import itertools as it
>>> [e for t in it.zip_longest(list1, list2) for e in t if e is not None]
['4,5', '1,3', '5,3', '6,4', '1,2', '8,8', '0,4', '6,2']
If there is a possibility of None as legit data in your lists, use a sentinel object instead:
sentinel=object()
[e for t in it.zip_longest(list1, list2, fillvalue=sentinel) for e in t if e is not sentinel]
Related
This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 2 years ago.
I want to retain the original list while manipulating it i.e I'm using it in a loop and have to perform some operations each iteration so need to reset the value of a list. Initially, I thought it was a problem with my loops but I have narrowed it down to.
inlist=[1,2,3]
a=inlist
a.pop(0)
print(a)
print(inlist)
gives an output of
[2,3]
[2,3]
Why am I not getting
[2,3]
[1,2,3]
It is applying pop to both a and inlist.
Let me explain with Interactive console:
>>> original_list = [1, 2, 3, 4] # source
>>> reference = original_list # 'aliasing' to another name.
>>> reference is original_list # check if two are referencing same object.
True
>>> id(reference) # ID of referencing object
1520121182528
>>> id(original_list) # Same ID
1520121182528
To create new list:
>>> copied = list(original_list)
>>> copied is original_list # now referencing different object.
False
>>> id(copied) # now has different ID with original_list
1520121567616
There's multiple way of copying lists, for few examples:
>>> copied_slicing = original_list[::]
>>> id(copied_slicing)
1520121558016
>>> import copy
>>> copied_copy = copy.copy(original_list)
>>> id(copied_copy)
1520121545664
>>> copied_unpacking = [*original_list]
>>> id(copied_unpacking)
1520123822336
.. and so on.
Image from book 'Fluent Python' by Luciano Ramalho might help you understand what's going on:
Rather than 'name' being a box that contains respective object, it's a Post-it stuck at object in-memory.
Try doing it this way
a = [1,2,3]
b=[]
b.extend(a)
b.pop(0)
Although what you are doing makes sense but what is happening is that you are just assigning another variable to the same list, which is why both are getting affected. However if you define b(in my case) as an empty list and then assign it, you are then making a copy as compared to another variable pointing to the same list.
This question already has answers here:
How to extract the n-th elements from a list of tuples
(8 answers)
Closed 3 years ago.
I have this list:
[('5.333333333333333', 'n04'), ('5.0', 'n01'), ('3.9936507936507932', 'n03'), ('2.4206349206349205', 'n05'), ('1.9629629629629628', 'n02')]
and I like to have the list like this:
[n04, n01, n03, n02, n04]
how to do it? I have spend too many houres on this problem.
Help please!
You can use a list comprension to iterate over the list and pick out the values you are interested in and put them in a new list
my_list = [('5.333333333333333', 'n04'), ('5.0', 'n01'), ('3.9936507936507932', 'n03'), ('2.4206349206349205', 'n05'), ('1.9629629629629628', 'n02')]
my_new = [item[1] for item in my_list]
print(my_new)
OUTPUT
['n04', 'n01', 'n03', 'n05', 'n02']
Try:
x,y=zip(*[('5.333333333333333', 'n04'), ('5.0', 'n01'), ('3.9936507936507932', 'n03'), ('2.4206349206349205', 'n05'), ('1.9629629629629628', 'n02')])
y=list(y)
print(y)
Outputs:
['n04', 'n01', 'n03', 'n05', 'n02']
I am an extremely begginer learning python to tackle some biology problems, and I came across lists and its various methods. Basically, when I am running print to my variable I get None as return.
Example, trying to print a sorted list assigned to a variable
list1=[1,3,4,2]
sorted=list1.sort()
print(sorted)
I receive None as return. Shouldn't this provide me with [1,2,3,4]
However, when printing the original list variable (list1), it gives me the sorted list fine.
Because the sort() method will always return None. What you should do is:
list1=[1,3,4,2]
list1.sort()
print(list1)
Or
list1=[1,3,4,2]
list2 = sorted(list1)
print(list2)
You can sort lists in two ways. Using list.sort() and this will sort list, or new_list = sorted(list) and this will return a sorted list new_list and list will not be modified.
So, you can do this:
list1=[1,3,4,2]
sorted=sorted(list1)
print(sorted)
Or you can so this:
list1=[1,3,4,2]
list1.sort()
print(list1)
This question already has answers here:
Is there a built in function for string natural sort?
(23 answers)
Closed 3 years ago.
I have a list of strings that I am trying to organize numerically it looks like this :
List=['Core_0_0.txt', 'Core_0_1.txt','Core_0_2.txt',...'Core_1_0.txt','Core_2_3.txt', ]
but when I sort it sorted(List)
It doesn't sort the list properly.
It's very important that I keep the values as strings and they must be ordered by the number; I.E. 0_1, 0_2,0_3....31_1, they all have Core_X_X.txt How would I do this.
If you can assume all your entries will look like *_N1_N2.txt, you can use the str.split method along with a sorting key function to sort your list properly. It might look something like this
sorted_list = sorted(List, key = lambda s: (int(s.split("_")[1]), int(s.split("_")[2].split(".")[0])))
Essentially, this internally creates tuples like (N1, N2) where your file is named *_N1_N2.txt and sorts based on the N1 value. If there's a tie, it will resort to the N2 value.
Your question is a possible duplicate of another question.
Which I am posting for you here again.
you just need to change 'alist' to your 'List'.
import re
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
'''
alist.sort(key=natural_keys) sorts in human order
http://nedbatchelder.com/blog/200712/human_sorting.html
(See Toothy's implementation in the comments)
'''
return [ atoi(c) for c in re.split(r'(\d+)', text) ]
alist=[
"something1",
"something12",
"something17",
"something2",
"something25",
"something29"]
alist.sort(key=natural_keys)
print(alist)
yields
['something1', 'something2', 'something12', 'something17', 'something25', 'something29']
This question already has answers here:
Pandas Passing Variable Names into Column Name
(3 answers)
Closed 4 years ago.
I am trying to read unique values for columns in list but unable to put variable correctly in a way that it becomes a command. If i run c_data.ABC.unique() directly then i get list of unique values in ABC column. Please suggest what is going wrong.
import pandas as pd
c_data=pd.read_csv("/home/fileName.csv")
list=['ABC','DEF']
for f in list:
cl="c_data.{}.unique()".format(f)
print(cl)
Output:
c_data.ABC.unique()
c_data.DEF.unique()
You should definetly check on these indexing basic in pandas. So, about your answer you can use the most basic indexing by brackets [] and string column name, for example c_data['ABC'], so you can iterate like this:
c_data = pd.read_csv("/home/fileName.csv")
list = ['ABC', 'DEF']
for f in list:
print(c_data[f].unique())
If you want/need to use format method, you can just replace column name with formatted string:
c_data = pd.read_csv("/home/fileName.csv")
list = ['ABC', 'DEF']
for f in list:
print(c_data['{0}'.format(f)].unique()])
Also, you can use bracket indexing with a list of string, which will give you another DataFrame. Then you can iterate over DataFrame itself which will give you column names:
c_data = pd.read_csv("/home/fileName.csv")
f_data = c_data[['ABC', 'DEF']]
for f in f_data:
print(f_data[f].unique())