Questions tagged [list-comprehension]
A syntactic construct which provides a concise way to create lists in a style similar to the mathematical set-builder notation. Since several languages support list comprehensions, please use this tag in conjunction with the tag of a programming language.
6,585
questions
0
votes
0
answers
63
views
List comprehension with mix of for-loops and if-conditions
So I have the following piece of code from my reddit bot:
for sorting in self.possible_sortings:
if self.sorting_flags[sorting]:
if self.sorting_timeframe_possible_flag[sorting]:
...
1
vote
2
answers
21
views
Nested Dictionaries - Grab top-level keys where specified field in sub-dictionaries satisfies criteria
This is a simple question but one which I'm having trouble finding an answer to. Data example:
nested = {
"Moli": {
"Buy": 75,
"Sell": 53,
&...
0
votes
0
answers
21
views
Remove items from a dict if their key is not in a list - improve performance
I need to find the elements in a Python dictionary, whose keys are NOT present in a list.
I tried doing it in a very simple way:
import random
dict_dim = 100000
number_good_keys = 1000
complete_dict ...
0
votes
1
answer
33
views
Dictionary Comprehension within a List Comprehension
I have a list of dictionaries, that I'm modifying values in. I have a for loop that works as expected.
show_mac = [{'mac': '0000.0000.0000', 'port': 'GigabitEthernet1/1', 'type': 'dynamic', 'vlan': '1'...
1
vote
3
answers
57
views
Python: Format datetime string in a list of dictionaries
I currently have the following where the AllergiesList can be one or more dicts.
{
"AllergiesList": [
{
"Date": "2021-09-03T00:00:00",
"Description&...
0
votes
1
answer
29
views
How can I loop through every item of multiple list with special condition?
I have 2 dataframes as below:
df1:
df1 = pd.DataFrame({'feature1':['a1','a1','a1','b1','b1','b1'], 'value': [1,2,3,4,5,6]})
df1
df2:
df2 = pd.DataFrame({'feature1':['c1','c1','c1','c2','c2','c2'], '...
-1
votes
3
answers
33
views
Why does Python list comprehension seem to behave differently than list "multiplication"? [duplicate]
Asking out of curiosity. For the sake of making a point I was trying to make a function that returns an "identity matrix" of n dimensions and then printing it in the most concise way.
First ...
0
votes
3
answers
52
views
Iterating through lists of lists in Python while keeping data structure
How can I iterate through lists of lists while keeping a lists data structure?
Here is the case:
w = [3, 3]
z = [[1, 1, 1], [2, 2]]
lst = []
for x, y in zip(w, z):
for u in y:
lst.append(...
0
votes
1
answer
38
views
Add two external variables via list comprehension
im learning list comprehension but don't know if i can add a sum two variables via list comprehension to a list.
So is it possible to express below code in a list comprehension?
#Make some rolls, and ...
-1
votes
1
answer
24
views
How can I write a python code that searches for a word in a string and then prints the string if word is present
Here is a scenario:
Given:
facility_list = ['port', 'airport']
location_list =[ 'new york', 'Manchester', 'lagos port','florida port', 'london','Durban airport' ]
Task:
For each location in ...
-1
votes
0
answers
43
views
Create even pairs from the values for key in python dictionary [duplicate]
I have a dictionary like this lets say 'ov' (as shown below):
{
'N1':
[
[
datetime.datetime(2022, 6, 2, 23, 48, 57, 296000),
datetime.datetime(...
0
votes
2
answers
40
views
"List indices must be integers or slices, not list" when clipping unwanted min valuable from list with one liner
mlist = [["Rachel", -50],["Mawer", -50],["Sheen",-50],["Shaheen",51]]
list1 = []
x = sorted(mlist, key = lambda x : x[1])
print(x[1])
x = [x for x in x if x[x]...
0
votes
0
answers
33
views
two empty list for list comprehension
How can I do such code in list comprehension ??
from itertools import combinations
remove_list = []
reamin_list = []
for m,n in combinations([0,1,2,3,4,0,1],2):
if (m or n) in remove_list:
...
1
vote
1
answer
37
views
Remove multiple elements from list using regex matching
I have an excel workbook that has sheet names as Countries. Along with those sheets, there are additional sheets that I do not want to process. Hence I am trying to eliminate those sheets and keep ...
-1
votes
1
answer
40
views
How to extract middle letters in a string?
How can I use list comprehension to extract all the middle letters of all the strings in Q[1]:
Q = [ ["Elizabeth","Victoria","Elizabeth"],
["Eleanor",&...
0
votes
1
answer
29
views
extract values into new column for each unique values in another column
I have a dataframe and a sample of it looks like this
review_id ngram date rating attraction indo
4 bigram 2021 10 uss sangat lengkap
359 ...
0
votes
1
answer
23
views
Generate hailstone sequence in Python using list comprehension [duplicate]
I have the following code which generates a hailstone sequence of numbers given a user specified positive integer.
n = int(input("Enter a number: "))
seq = [n]
while n > 1:
n = 3 * ...
0
votes
1
answer
30
views
Nested List Comprehensions transpose matrix
I just started out my journey with Python and I can't figure out how this loop transposes the matrix!
Can someone give a detailed explanation?
matrix = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]...
1
vote
1
answer
23
views
Access a list of columns to be evaluated in a Comprehension Expression
There is this dataframe called frame with columns: Age, Maturity, Gender, Height which has values 'PASSED' or 'FAILED'.
I want to create a new column called result and count the number of a subset of ...
-1
votes
0
answers
39
views
list comprehension doesn't give expected out as in the for loop
I was working on an assignment based on list and list comprehension:
names = ['A','B','C','A','D','E','F','G','H','E','D']
my_list=[]
for x in names:
if x not in my_list:
my_list.append(...
1
vote
3
answers
57
views
How to split a list using marker elements?
I'm trying to split a list in Python using some elements as markers. For example, consider the list:
["marker1", "elem1", "elem2", "marker2", "elem3"]
...
0
votes
2
answers
68
views
remove elements of one list from another list python
Is there a pythonic way to remove elements from one list to another list? (Not removing all duplicates)
For example, given [1, 2, 2, 3, 3, 3] (original list) and [1, 2, 3] (elements to be removed). It ...
-3
votes
1
answer
47
views
Which is the best way for performance in Python
Here is a members list and each member has a group name and a member name.
members = [
{"group": "python", "name": "best"},
....
]
When new member is ...
-2
votes
0
answers
48
views
How to rewrite for loop using a list comprehension [duplicate]
can you please help me understand how can I rewrite the following for loop using a list comprehension:
companies = ('Apple', 'Amazon', 'Alphabet', 'Microsoft', 'Visa')
companies_new = list()
for ...
-3
votes
1
answer
58
views
Parsing a very large array with list comprehension is slow
I have an ultra large list of numerical values in numpy.float64 format, and I want to convert each value, to 0.0 if there's an inf value, and parse the rest the elements to simple float.
This is my ...
1
vote
1
answer
46
views
change to uppercase if character before is an underscore
I have a string
inputstring = "ini adalah salah satu theme park yang terkenal yaitu __u__n__i__v__e__r__s__a__l __s__t__u__d__i__o , di dalam banyak sekali permainan menarik seperti untuk remaja ...
2
votes
2
answers
29
views
TapeEquilibrium - Python
I'm studying through Codility and I'm doing this lesson.
So the basically solution that I thought at first time was:
#SOLUTION 1
def solution(A):
diff = []
for x in range(1,len(A)):
...
1
vote
4
answers
39
views
best way of counting number of items based on condition python
Hi guys I have multiple conditions to check on a array of objects for example :
My sample array is like this
[{"id":1 , "type":"viw"},{"id":1 , "type":...
0
votes
0
answers
31
views
Python: search a list for multiple sublists efficiently
I'm trying to find an efficient solution for the following problem: I have multiple short, unique lists which are stored in a dict and mapped to strings. (Though this isn't set in stone as the lists ...
0
votes
2
answers
34
views
Order list by key and build sum over list items - python
I want to create a shopping list based on meal selections in an ecxel file.
What I have is a list list_flat_ingredients imported from a csv with this format:
[ingredient_amount, ingredient_unit, ...
0
votes
2
answers
77
views
List comprehension with lambda
How can I rewrite this loop using lambda and list-comprehension?
n = 17
e = 0
for i in range(0, n):
e += 1 / factorial(i)
print(e)
So far I have tried this...but it's not working
lst = [item for ...
0
votes
2
answers
60
views
Splitting strings without resulting in 2-D list
How do I split strings in a list without resulting in a 2-D list?
list1:['Ben&Jerry', 'Julia', 'Sally&Don', 'Tom', 'Tracy&Jim']
to output:
['Ben','Jerry','Julia','Sally', 'Don','Tom','...
-1
votes
2
answers
52
views
Change all strings in list of lists but the last element
I am trying to use list comprehension to create a new list of lists of strings in which all strings but the last will be lowercased. This would be the critical line, but it lowercase all strings:
[[...
-1
votes
3
answers
26
views
List Comprehension for List of Dictionary to get Values Separately for Each Key
I want to get the city names and their respective population in separate list from a given list of dictionary. I have achieved this using naive method and using map() function as well but I need it to ...
0
votes
4
answers
68
views
Most pythonic way to get one item from a list? [duplicate]
Say I have a list of dicts where dict['id'] is unique, and I want to access one specific dict.
This is how I would usually do that, more or less.
d_ = [d for d in list_of_dicts where d['id']=='...
0
votes
1
answer
41
views
Are list comprehensions fully evaluated before being used in the rest of the code?
Consider the following code.
with open('filename.txt', 'r') as f:
var = [element for element in f.readlines()][3]
This question concerns the internals of Python, rather than the result.
Does ...
0
votes
2
answers
36
views
Make new list from source list at index 0, find matching items in second list and append to that new list at index 1
I have a scrip that I'd like to take source data list1 and pull data from it. models is a list that contains index[0] of each item in list1 and now I'd like to append or insert a specific item from ...
0
votes
5
answers
63
views
Filter nested list with list comprehension based on other list in python
I have two lists like this:
a = [[1,2,3],[2,3,4],[5,6,7],[7,8,9]]
b = [1,2]
I would now like to filter list a, to keep only the items which contain the items in list b. So the desired output would ...
0
votes
2
answers
28
views
Element-wise appending of 2D lists? [duplicate]
I want to concatenate 2D lists to the end of a list_log, as follows:
list_log = []
list1 = [[0.0], [1.7], [8.4], [20.1], [29.3], [41.8], [74.1], [61.9]]
list2 = [[1.0], [3.6], [13.5], [31.5], [50.3], ...
1
vote
6
answers
67
views
Taking bitwise '&' of arbitrary number of lists
I have an arbitrary number of lists that I want to take the boolean & of. For example for 2 lists, I have
x = [0, 1, 0, 0]
y = [1, 1, 0, 1]
[np.array(x) & np.array(y) for x,y in zip(x, y)]
[0,...
1
vote
2
answers
73
views
2 List Comprehension in python [duplicate]
I tried to write this, where s is just an int
for box in current_boxes:
for i in range(len(box)):
box[i] = box[i]*s
all_boxes.append(box)
as a list comprehension. But my ...
3
votes
3
answers
87
views
All permutations of numbers 1...N using list comprehension (without itertools)
I am currently using Python 3.7.7, and I posed a coding challenge for myself.
I would like to list all permutations of integers from 1 to N using a one-line code (perhaps a list comprehension). I ...
0
votes
1
answer
31
views
How can I fix a KeyError occurring while iterating through a list of dictionaries extracting values? [duplicate]
I'm trying to extract the value associated with lowPrice in a list of dictionaries using a list comprehension.
I'm having an issue (I think) because the "lowPrice" key isn't found in the ...
2
votes
3
answers
38
views
Python: How do I group recurring consecutive digits of only one type?
I wrote this program to find certain consecutive recurring digits in a string and group them. The string only contains 0 and 1, and I want to shorten the recurring zeros by converting them to a number....
0
votes
1
answer
95
views
Using map() on a function with multiple inputs to get rid of for loops
Context:
I have a function to upsample multiple arrays that I want to write as efficiently as possible (because I have to run it 370000 times).
This function takes multiple inputs and is composed of 2 ...
2
votes
3
answers
57
views
How to make if inside for loop using lambda?
I have list_a and string_tmp like this
list_a = ['AA', 'BB', 'CC']
string_tmp = 'Hi AA How Are You'
I want to find out is there any of string_tmp items in the list_a, if it is, type = L1 else type = ...
0
votes
2
answers
39
views
I want print items in list one by one using list comprehension in python. How can do that?
itemlist = [("Tatamotors",483.4568), ("M&M",953.8045),("TVSmotors",712),("AshokLeyland",142.2567)]
print([f"Item {stock} : Price = {price}" for ...
1
vote
2
answers
88
views
Python list/dict comprehension summing a dict list key by another key in the same dict
Been thinking how to convert this to a one liner if possible:
activities =
[ {'type': 'Run', 'distance': 12345, 'other_stuff': other ...},
{'type': 'Ride', 'distance': 12345, '...
0
votes
2
answers
55
views
Conditionally adding 1 or 2 items into a list using a list comprehension
Is there a way to insert one or two items into a list using a list comprehension depending on some condition using only one for loop?
For example if I wanted to iterate over n numbers, if a number is ...
-1
votes
2
answers
34
views
PYTHON3 - How to use List Comprehension with a numpy array, to unpack a tuple of Lists, to avoid running for loop multiple times
In Short ->
How to write this expression correctly?? ->
[(self._mean,self._var,self._priors)] = [ ([X[y==c].mean(axis=0)] , [X[y==c].var(axis=0)],[X[y==c].shape[0] / n_samples ]) for c in self....