7,146
questions
3
votes
3
answers
99
views
python list comprehension -- two loops with three results?
I can ask my question best by just giving an example. Let's say I want to use a list comprehension to generate a set of 3-element tuples from two loops, something like this:
[ (y+z,y,z) for y in ...
-2
votes
0
answers
22
views
A simple debugging print statement in python changes the logic of execution. Expected output occurs after removing the debugging print [duplicate]
Here is my code on an attempt to convert a simple list comprehension to one using a map function.
A = range(4)
B = range(4)
# Step 1: Generate pairs using map
result_pairs = map(lambda x: ...
-2
votes
0
answers
36
views
How to optimize this Python loop with list comprehensions? [duplicate]
Here's my current code:
result = []
for item in my_list:
if condition(item):
result.append(transform(item))
I'm trying to optimize a Python loop that iterates over a list, checks a ...
-4
votes
2
answers
360
views
Python comprehension with different number of elements
The general problem
I have a case where I'm generating an element comprehension with a different cardinality to the input source. This cardinality should not be a multiple of the original (data-driven)...
1
vote
0
answers
61
views
Two if statements in a list comprehension [duplicate]
Looking at another question, I saw what I assumed was a simple typo or misunderstanding of list comprehension syntax -- but it actually worked!
This is a simplified version of the code in that ...
-1
votes
3
answers
56
views
update dictionaries in the list comprehension
There is a dictionary:
d = [{"a":1, "b":2},{"a":3, "b":4},{"a":5, "b":6}]
I'd like to update values of keys b.
d = [{**m}.update({"b&...
0
votes
3
answers
74
views
printing out a sequence using list comprehension instead of for loop
Using python,I want to generate a sequence [0,2,6,12,20,30,42,56,72,90];
The logic that I've figured out is like this
i,j =0,0
for i in range(1,10):
j+= 2*i
print(j)
Instead of for loop, I need to ...
-2
votes
0
answers
19
views
Getting all elements in a response into a list for further usage? [duplicate]
I have fixed this issue:
Get IDs from JSON response
with great help, but given a helper function as this:
def get_pp_for_bid(data):
return next(unit["reference"]
for x in data
...
0
votes
3
answers
47
views
Moving corner points of a rectangle in Python: is there a more elegant/compact solution?
I need to move the corner points of a rectangle by a given amount. I'm given an list of 4 3D points, each of which is a list of coordinates ([x,y,z]).
I have this, and it works OK, but feels awkward (...
3
votes
8
answers
189
views
Is there a way to do this with a list comprehension?
I have a list that looks something like this:
data = ['1', '12', '123']
I want to produce a new list, that looks like this:
result = ['$1', '1', '$2', '12', '$3', '123']
where the number after the $ ...
0
votes
0
answers
18
views
How does the parenthesis affect the walrus operator?
I was doing question number 238 on leetcode and I wanted to use the walrus operator as practice. Here's the part of the code that I have an issue with:
def productExceptSelf(self, nums: List[int]) -&...
1
vote
2
answers
56
views
Use list comprehension with if, else, and for-loop while only keeping list items that meet a condition
I use list comprehension to load only the images from a folder that meet a certain condition.
In the same operation, I would also like to keep track of those that do not meet the condition. This is ...
0
votes
1
answer
59
views
R function vector comprehension
It is surprising that I do not seem to able to find any source on this topic. How to do vector comprehension in R? That is, suppose that :
foo <- function(a,b,c){
print(c(a,b,c))
}
x <- c(1,...
0
votes
2
answers
87
views
Why are all rows of my matrix the same as the last row?
Can someone please help me find fault in my code? If I create a blank 2D matrix with static initial value, it returns the correct transposed matrix. Whereas if I create a blank matrix using a for loop,...
0
votes
2
answers
75
views
temporary variable in list comprehension [duplicate]
Is there a concise way to rewrite the following code fragment as a list comprehension?
nsms = []
for line in lines:
fields = line.split(';')
if len(fields) > 4 and fields[4] == 'NSM':
...
3
votes
3
answers
60
views
How to get the name of column with second highest value in pyspark dataframe
I have a PySpark dataframe looking like this:
id
trx_holiday
trx_takeout
trx_pet
max_value
MAX
1
12.5
5.5
9.5
12.5
trx_holiday
2
3.0
14.0
6.7
14.0
trx_takeout
I want to create a second column ...
1
vote
2
answers
80
views
How does this Haskell List Comprehension evaluate?
I'm learning Haskell and I came across this example in relation to list comprehensions:
[x | xs <- [[(3,4)],[(5,4),(3,2)]], (3,x) <- xs]
The answer given is:
[4,2].
Why isn't the answer [(3,4),(...
-1
votes
3
answers
63
views
Trying to get dict[k] from a dict in a list of dicts for k in list or string
I have a couple dictionaries with differing values for the same keys.
I have a list of these dicts and I want to return the values from only 1 of the dicts based on the matched keys inside a different ...
0
votes
2
answers
60
views
Condition in python lists comprehensions
friends-coders! Help with condition in lists comprehensions at python code, please. Where are mistake in that syntax?
matrix = [
[matrix[i][j] = '.' if matrix[i][j] % 2 == 0 else matrix[i][j] = '*' ...
-1
votes
1
answer
81
views
Using list comprehension while creating a pandas pipeline throws function object not iterable error
I have to create a Pandas dataframe from a csv file using a pipeline.
The src csv file may contain any number of columns with header/name containing the string 'SLA'. Sample data below:
While ...
0
votes
0
answers
36
views
Iterate to a nested list in a pythonic way [duplicate]
I have the following payload:
payload = [{
"identification": {
"corporationName": "Test",
"code": 1234
},
"locations": [
{
&...
1
vote
1
answer
60
views
How to create vector elements in pairs in a FOR loop in OpenSCAD
My aim is to create 2D vector elements in pairs, using a FOR loop. Consider the following example (not my real example - just something simplified to describe the problem):
step1 = [ for (i=[1:5])...
0
votes
1
answer
46
views
Why does comprehension only work with tuples when unpacking in Python?
I tried to use list comprehension on a tuple and it worked fine when unpacking, but not when assigning to a single variable.
If I run the following code
var1, var2, var3 = (i for i in range(3))
var1 =...
0
votes
1
answer
48
views
replace() and if/else in list comprehension to create a new list
The quiz problem is supposed to replace the file name .hpp with .h while keeping the rest using list comprehension. Some posts suggest that I must put in [do_something else if condition for x in range]...
-3
votes
3
answers
96
views
How to improve a List Comprehension in python
I'm attempting to convert this function to a List Comprehension but I have to do a work around using set() to prevent False from repeating.
And the locations are not in order. e.g. {0, 12, 5} instead ...
-1
votes
1
answer
34
views
search for elements of a list as substring in another list python
I have 2 lists. I want to find the elements in ls2 where any element of ls1 is a substring. I would like to return a list of ls2 elements along with the substring that was searched and found from ls1
...
-1
votes
1
answer
43
views
How do I create an arithmetic progression as a list of lists [closed]
I want to create a continuous arithmetic progression as a list of lists.
I came up with this solution:
def foo(start: int = 1, end: int = 20, step: int = 4) -> list:
"""Return ...
0
votes
1
answer
88
views
Create deck of multiple decks of cards using list comprehension [duplicate]
I've created a Card object:
class Card:
def __init__(self, rank, suit, d=0):
self.rank = rank
self.suit = suit
self.deck_index = d
I can make a list of Cards that ...
1
vote
2
answers
39
views
normalizing weights efficiently in python
I want to normalize weights within subgroups in a list/array. I have a working version now but it looks cumbersome and i feel there is a much more efficient way to do this. Btw, I have experience with ...
-2
votes
1
answer
62
views
How to efficiently filter a large list in Python using multiple conditions?
I'm working on a Python project where I need to filter a large list of dictionaries based on multiple conditions.
Here's a simplified example of the data structure I'm dealing with:
data = [
{&...
0
votes
5
answers
64
views
How to get an tuple of coordinates from a list inside another list
I have the following list:
list = [[0, 0, 1],
[1, 0, 0],
[0, 1, 0]]
My goal is to return from this list, a set of tuples that contain the coordinates (row, column) of each value ...
2
votes
1
answer
60
views
Remove permutations of tuples of a Pythagorean triple in haskell
the haskell function: pytri that I have written is a comprehension that takes an integer value n
as input and returns a list of all triples (a, b, c) with a, b, c ≤ n
that satisfy the Pythagorean ...
0
votes
0
answers
16
views
Pandas timedelta in List Comprehension [duplicate]
I am attempting to create a new if-else column in a df with a list comprehension:
df['col'] = ['y' if (x - df['a']).dt.days < 365 else 'n' for x in df['b']]
Columns A & B are datetimes. If ...
2
votes
3
answers
73
views
List comprehension to return list if value is non-existent [duplicate]
I'm aiming to use list comprehension to return values in a list. Specifically, if 'x' is in a list, I want to drop all other values. However, if 'x' is not in the list, I want to return the same ...
0
votes
0
answers
34
views
Is it possible to populate list of values in ansible's defaults/main.yml
Having a custom inventory data structures and input arguments of a role, I want to populate those input arguments from inventory data structures. Is it possible to somehow populate list in a loop?
For ...
0
votes
1
answer
32
views
How to compare cells data with columns using python
I have an excel with some data like below imageexcel data
If you compare column A WITH column C(A4 present in C18 and A5 present in C17) so these two will true and other is false, how to write code in ...
-4
votes
2
answers
64
views
convert range(0,10) to a list of lists in Python3 [closed]
I need to create a list of lists from a range:
for example range(0,10) -->[[0,5],[6,10]]
I think possible to do it using list comprehension but cannot figure out a way for the same
I tried this ...
1
vote
1
answer
58
views
Do comprehensions in python call a function in the background?
I defined the following factorial function using recursion :
def factorial(n):
if n == 0:
return n
else:
return n*factorial(n-1)
Then, I defined the following function to ...
-1
votes
3
answers
66
views
How would I modify an outside variable within a list comprehension?
Python code:
i: int = 1
table: list = [[i, bit, None, None] for bit in h]
Expected behaviour: i needs to be incremented by 1 per iteration.
Pseudocode:
i: int = 1
table: list = [[i++, bit, None, None]...
0
votes
0
answers
45
views
Regular expression matching variable at end of string
I have some histograms in a .root file which are called "Name/NameEvent1Ch0", "Name/NameEvent1Ch1"... "Name/NameEvent1Ch31" ... "Name/NameEvent2Ch0"... "...
0
votes
0
answers
78
views
Combing two lists together with zip() function through list comprehension or plain function
I am new to this site. If anyone wants to combine two list I found the zip function works for both list comprehension and just as a function to combine both lists. The best explanation I heard for the ...
2
votes
3
answers
107
views
List comprehension to remove element from python list if it is only digits (even if there are "_" or "-" in it)
I have many lists like this
synonyms = ["3,2'-DIHYDROXYCHALCONE", '36574-83-1', '36574831', "2',3-Dihydroxychalcone", '(E)-1-(2-hydroxyphenyl)-3-(3-hydroxyphenyl)prop-2-en-1-one', ...
-1
votes
1
answer
54
views
Checking if any item in one set is in another set using a single comprehension possible?
I have the following check in my unit test:
assert any(pass1_task in (task for task in all_downstream_task_for_dl_task) for pass1_task in {'first_pass', 'first_cpp_pass'}), 'the test failed ...
0
votes
1
answer
34
views
Can I made use of comprehensions for comparing these lists of dictionaries?
As title. I'm trying to figure out a comprehension for this. Getting stuck adding complexity to the basic code I built so far. I feel like this would actually be easier in a comprehension, but I ...
-3
votes
1
answer
47
views
Python list of lists to one dimensional using comprehension [duplicate]
What would be the syntax to convert this loop into one line comprehension operator?
lst = [
[1,2,3],
[4,5,6],
[7,8,9],
[10,11,12]
]
all_records = []
for entry in lst:
all_records....
1
vote
2
answers
79
views
How to speed up word removal in a dataframe of word lists?
I am trying to remove non-dictionary words from a medium-sized (18k rows) pandas dataframe, but my approach is extremely slow. Basically, I have tried doing list comprehension and applying it to the ...
-1
votes
1
answer
92
views
Python function to return a new list containing the strings that are palindromes and have an even length
Practice Question:
Given a list of strings, write a Python function to return a new list containing the strings that are palindromes and have an even length.
For example:
Input: ["radar", &...
-4
votes
1
answer
39
views
Can some help me the list comprehension of the below for loop? [duplicate]
Create a list of all elements in the string “Yellow Yaks like yelling and yawning and #yesturday they yodled while eating yuky yams” by ignoring a,e,i,o,u in the element
I wrote the for loop:
...
-3
votes
1
answer
62
views
Converting For Loops To List Comprehensions [duplicate]
I was trying to understand List Comprehensions because I needed to improve performance on my project.
I believe this is how they work but please correct me if I am wrong.
To convert a for loop into a ...
2
votes
2
answers
88
views
List comprehension using take
I am having trouble understanding they way the next two lines of code work.
ghci> take 6 [[(i,j) | i<-[2,4]] | j<-[1,3,5]]
[[(2,1),(4,1)],[(2,3),(4,3)],[(2,5),(4,5)]]
ghci> take 6 [[(i,j)]...