How to split python3 List? [duplicate] - python-3.x

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']

Related

concatenate 2 lists in a certain order [duplicate]

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]

Add multiple value to a key in Python dictionary [duplicate]

This question already has answers here:
list to dictionary conversion with multiple values per key?
(7 answers)
Closed 2 years ago.
I am trying to add multiple value to a single key(if found) from a file in python. I tried below code but getting this error: AttributeError: 'str' object has no attribute 'append'
file=open("Allwords",'r')
list=sorted(list(set([words.strip() for words in file])))
def sequence(word):
return "".join(sorted(word))
dict= {}
for word in list:
if sequence(word) in dict:
dict[sequence(word)].append(word)
else:
dict[sequence(word)]=word
Thanks in advance for your help!
You should insert the first element by putting it into a list, so that you can append subsequent items to it later on. You can do it as follows -
file=open("Allwords",'r')
list=sorted(list(set([words.strip() for words in file])))
def sequence(word):
return "".join(sorted(word))
dict= {}
for word in list:
if sequence(word) in dict:
dict[sequence(word)].append(word)
else:
new_lst = [word] # Inserting the first element as a list, so we can later append to it
dict[sequence(word)]=new_lst
Now you will be able to append to it properly. In your case, the value you were inserting was just a string to which you wouldn't have been able to append. But this will work, since you are inserting a list at start to which you would be able to append to .
Hope this helps !

Looping thru JSON using Python? [duplicate]

This question already has answers here:
How can I parse (read) and use JSON?
(5 answers)
Closed 2 years ago.
How do you filter a records in JSON Array using Python?
Here's my Python code:
Sample Data Source: https://s3-eu-west-1.amazonaws.com/dwh-test-resources/recipes.json
In the "ingredients" i need to filter all records that contain bread. all string contain bread under the "ingredients" regardless if the string bread is upper case, lower case, plural or singular i should be able to filter it.
My python version is 3.
Lets say:
data = [{...json you have}]
Now we will check:
res = []
for i in data:
if 'bread' in i["ingredients"].lower():
res.append(i)
or simply:
res = [i for i in data if 'bread' in i["ingredients"].lower()]

How to delete an element by index from a numpy array in Python 3? [duplicate]

This question already has answers here:
How to remove specific elements in a numpy array
(13 answers)
Closed 3 years ago.
I want to delete an element from a numpy array by index.
The commands
arr = np.linspace(-5,5,10)
del arr[0]
The code above throws an error saying cannot delete array elements.
Using pop doesn't work either. What should I do?
You should use np.delete for it.
arr = np.linspace(-5,5,10)
arr = np.delete(arr, 0)

How to pass custom function to dataframe.apply with parameters other than row(axis=1) [duplicate]

This question already has answers here:
python pandas: apply a function with arguments to a series
(7 answers)
Closed 4 years ago.
I'm working on script that automatically generates full file path column using df.apply() as below.
def generate_filepath(row):
all_files = os.listdir(files_dir)
if row['FileName'] not in all_files:
return None
value = os.path.join(files_dir, row['FileName'])
return value
csv_df['FilePath'] = csv_df.apply(generate_filepath, axis=1)
I had to declare files_dir as a global variable and then use it in the function. Is there any other I can pass it as an argument along with df.apply?
Kindly help me with good suggestions
Why don't you curry your function?
https://www.python-course.eu/currying_in_python.php
or add another argument?
Edit: Jon Clements answer is better than mine

Resources