This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 5 years ago.
I'm trying iterate over lists in Python, but can't do it in an economic and pythonic way.
I can do in one dimension list:
api_time = ['hour', 'time']
text = 'What time is it?'
request = [r for r in api_time if r in text]
This outputs 'time', which is correct.
But when I start using two dimension list, I can't do it in one sentence.
api_time = ['hour', 'time']
api_weather = ['clime', 'rain']
apis = [api_time, api_weather]
How can I check this in one sentence?
You can use a double list comprehension:
>>> api_time = ['hour', 'time']
>>> api_weather = ['clime', 'rain']
>>>
>>> apis = [api_time, api_weather]
>>> text = 'What time is it?'
>>> [r for api in apis for r in api if r in text]
['time']
Or a simple list addition instead of nested lists:
>>> [r for r in api_time + api_weather if r in text]
['time']
Related
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.
I'm scraping a website and the needed output is a list of floats.
when scraping I'm getting back lists of the the floats in str.
after converting them to floats I want to combine them to one list so i can iterate over it and write it to csv.
for statname in data['athletes']:
l = list(statname['categories'][1]['totals'][10:12])
ast = (l[0])
nast = []
nast.append(ast)
a = list(nast)
sas = list(map(float, a))
print(sas)
result:
[8.8] [6.3] [6.2] [7.6] [3.0][3.8]
needed:
[8.8, 6.3, 6.2, 7.6...]
This should work:
sas = []
for statname in data['athletes']:
l = list(statname['categories'][1]['totals'][10:12])
ast = (l[0])
nast = []
nast.append(ast)
a = list(nast)
sas = sas + list(map(float, a))
print(sas)
Try using:
nast = []
for statname in data['athletes']:
l = list(statname['categories'][1]['totals'][10:12])[0]
nast.append(l)
sas = list(map(float, nast))
print(sas)
This question already has answers here:
How to get the cartesian product of multiple lists
(17 answers)
Closed 3 years ago.
I am new to python and am trying to create a new list from 2 other lists by appending each item in the list.
for number in num:
for names in name:
print(number+names)
num = [1,2,3,4,5]
name = ['Tom','Bob','Dave']
new_desired_list = [1Tom,1Bob,1Dave,2Tom,2Bob,2Data,3Tom,3Bob,3Dave..etc]
Seems like you want the cartesian product of both lists. For that you have itertools.product. In order to join the strings you could use string formatting:
from itertools import product
[f'{i}{j}' for i,j in product(num, name)]
# ['{}{}'.format(i,j) for i,j in product(num, name)] # for Python 3.6<
# ['1Tom', '1Bob', '1Dave', '2Tom', '2Bob'...
You could try appending a list ;)
l = []
numbers = [1,2,3,4,5]
names = ['Tom','Bob','Dave']
for number in numbers:
for name in names:
l.append(str(number) + str(name))
print(l)
Use list comprehension:
new_list = [str(i)+x for i in num for x in name]
Example:
>>> num = [1,2,3,4,5]
>>> name = ['Tom','Bob','Dave']
>>>
>>> new_list = [str(i)+x for i in num for x in name]
>>> new_list
['1Tom', '1Bob', '1Dave', '2Tom', '2Bob', '2Dave', '3Tom', '3Bob', '3Dave', '4Tom', '4Bob', '4Dave', '5Tom', '5Bob', '5Dave']
>>>
This question already has answers here:
Is there a zip-like function that pads to longest length?
(8 answers)
Closed 3 years ago.
I know a way to interleave two strings using Python but it works only if their lengths are equal:
u = 'Abcd'
l = 'Wxyz'
res = "".join(i + j for i, j in zip(u, l))
print(res)
This will give me the correct Output:AWbxcydz
But if the strings are u = 'Utkarsh' and l = 'Jain', the same method does not give the correct answer. Can someone suggest a way to do so?
Use zip_longest from itertools.
from itertools import zip_longest
u = 'Abcdefgh'
l = 'Wxyz'
res = "".join(i + j for i, j in zip_longest(u, l, fillvalue=''))
print(res)
This question already has answers here:
Split by comma and strip whitespace in Python
(10 answers)
Closed 4 years ago.
Input list example = ['listen, silent', 'dog, fog', 'colour, simple']
how do I return a nested list from the example in pairs, to look like this:
[[word1,word2], [word3,word4]...etc]
please, thank you
I have tried list comprehension,
my_list1 = [i[1] for i in my_list]
my_list2 = [i[0] for i in my_list]
but it took out only the first letter instead of word... hoping for it to look like;
[listen, silent],[dog, fog]...etc
You can split each word in the list using , as a separator:
l = ['listen, silent', 'dog, fog', 'colour, simple']
l = [elem.split(', ') for elem in l]
print(l)
Output:
[['listen', 'silent'], ['dog', 'fog'], ['colour', 'simple']]
This question already has answers here:
Splitting a list based on a delimiter word
(4 answers)
Closed 4 years ago.
I am trying to split a list that I have into individual lists whenever a specific character or a group of characters occur.
eg.
Main_list = [ 'abcd 1233','cdgfh3738','hryg21','**L**','gdyrhr657','abc31637','**R**','7473hrtfgf'...]
I want to break this list and save it into a sublist whenever I encounter an 'L' or an 'R'
Desired Result:
sublist_1 = ['abcd 1233','cdgfh3738','hryg21']
sublist_2 = ['gdyrhr657','abc31637']
sublist 3 = ['7473hrtfgf'...]
Is there a built in function or a quick way to do this ?
Edit: I do not want the delimiter to be in the list
Use a dictionary for a variable number of variables.
In this case, you can use itertools.groupby to efficiently separate your lists:
L = ['abcd 1233','cdgfh3738','hryg21','**L**',
'gdyrhr657','abc31637','**R**','7473hrtfgf']
from itertools import groupby
# define separator keys
def split_condition(x):
return x in {'**L**', '**R**'}
# define groupby object
grouper = groupby(L, key=split_condition)
# convert to dictionary via enumerate
res = dict(enumerate((list(j) for i, j in grouper if not i), 1))
print(res)
{1: ['abcd 1233', 'cdgfh3738', 'hryg21'],
2: ['gdyrhr657', 'abc31637'],
3: ['7473hrtfgf']}
Consider using one of many helpful tools from a library, i.e. more_itertools.split_at:
Given
import more_itertools as mit
lst = [
"abcd 1233", "cdgfh3738", "hryg21", "**L**",
"gdyrhr657", "abc31637", "**R**",
"7473hrtfgf"
]
Code
result = list(mit.split_at(lst, pred=lambda x: set(x) & {"L", "R"}))
Demo
sublist_1, sublist_2, sublist_3 = result
sublist_1
# ['abcd 1233', 'cdgfh3738', 'hryg21']
sublist_2
# ['gdyrhr657', 'abc31637']
sublist_3
# ['7473hrtfgf']
Details
The more_itertools.split_at function splits an iterable at positions that meet a special condition. The conditional function (predicate) happens to be a lambda function, which is equivalent to and substitutable with the following regular function:
def pred(x):
a = set(x)
b = {"L", "R"}
return a.intersection(b)
Whenever characters of string x intersect with L or R, the predicate returns True, and the split occurs at that position.
Install this package at the commandline via > pip install more_itertools.
#Polyhedronic, you can also try this.
>>> import re
>>> Main_list = [ 'abcd 1233','cdgfh3738','hryg21','**L**','gdyrhr657','abc31637','**R**','7473hrtfgf']
>>>
>>> s = ','.join(Main_list)
>>> s
'abcd 1233,cdgfh3738,hryg21,**L**,gdyrhr657,abc31637,**R**,7473hrtfgf'
>>>
>>> items = re.split('\*\*R\*\*|\*\*L\*\*', s)
>>> items
['abcd 1233,cdgfh3738,hryg21,', ',gdyrhr657,abc31637,', ',7473hrtfgf']
>>>
>>> output = [[a for a in item.split(',') if a] for item in items]
>>> output
[['abcd 1233', 'cdgfh3738', 'hryg21'], ['gdyrhr657', 'abc31637'], ['7473hrtfgf']]
>>>
>>> sublist_1 = output[0]
>>> sublist_2 = output[1]
>>> sublist_3 = output[2]
>>>
>>> sublist_1
['abcd 1233', 'cdgfh3738', 'hryg21']
>>>
>>> sublist_2
['gdyrhr657', 'abc31637']
>>>
>>> sublist_3
['7473hrtfgf']
>>>