Questions tagged [list-comprehension]

0

votes
0

answer
14

Views

Python3: list comprehensions and stack frames

Consider this function: def quux(): i = 42 print([i for x in [1]]) Result: [42] Therefore, I assume that local vars are visible in list comprehensions. Now consider this: def foo(): return currentframe().f_back.f_locals["i"] def quux(): i = 42 print([foo() for x in [1]]) Result in: KeyError: 'i' I...
Martin Sustrik
1

votes
1

answer
67

Views

Counting/grouping datapoints: for-loop or list comprehension?

I’m trying to count a number of integer data points within 1000’s groups. Let’s assume we have 10,000 data points in the range 0..999999: import random random.seed(123456) # generate a reproducable sequence # make 10000 numbers in range 0..99999 maxn = 99999 numbers = [random.randint(0,maxn) f...
Moonbase
3

votes
2

answer
20

Views

Find elements in a list of which all elements in another list are factors, using a list comprehension

I have a list of numbers from which I have extracted common factors of all these numbers. For example, from list b = [16, 32, 96], I have produced list_of_common_factors = [1, 8, 16, 2, 4]. I have another list of integers, a and I wish to extract the numbers from list_of_common_factors of which all...
kashveyron
0

votes
1

answer
20

Views
-2

votes
0

answer
21

Views

Question generator is giving NameError, how can I reformat to iterate/call question?

I found this code on an old SO post as it was exactly what I was looking for but when I run the code I get an {NameError} because neither the question1 or question2 are ever called. Trouble is I'm still learning python and I'm not sure how to solve this. I'm still working my way through Zed Shaws le...
0

votes
1

answer
29

Views

List of pairs into pair of Lists Haskell

Basically I have this exercise: Using list comprehensions, write a polymorphic function: split :: [(a, b)] -> ([a], [b]) which transforms a list of pairs (of any types) into a pair of lists. For example, split [(1, 'a'), (2, 'b'), (3, 'c')] = ([1, 2, 3], "abc") This was the way I wrote the function...
Nicekor
1

votes
3

answer
47

Views

Python Raising Errors within List Comprehension (or a better alternative)

I have a nested structure read from a json string, that looks similar to the following... [ { "id": 1, "type": "test", "sub_types": [ { "id": "a", "type": "sub-test", "name": "test1" }, { "id": "b", "name": "test2", "key_value_pairs": [ { "key": 0, "value": "Zero" }, { "key": 1, "value": "One" } ] }...
MatBailie
0

votes
0

answer
13

Views

How to dynamically indicate the start as well as the end of a set of conditions within a DataFrame?

I I seek to create an indicator column in a dataframe that looks at the values of entry and exit column and creates a window that has the following logic: Find earliest date where entry is a 1 (1/3/2019) and mark window as 1. Window remains 1 until exit is 1 (1/5/2019). Window then becomes 0 until i...
rer49
1

votes
4

answer
943

Views

Read all columns from CSV file?

I am trying to read in a CSV file and then take all values from each column and put into a separate list. I do not want the values by row. Since the CSV reader only allows to loop through the file once, I am using the seek() method to go back to the beginning and read the next column. Besides using...
astra
1

votes
2

answer
89

Views

Speed issues with pandas and list comprehensions

I have a dataset with 4m rows of data, and I split this into chunks using pd.read_csv(chunk size...) and then perform some simple data cleaning code to get it into a format I need. tqdm.pandas() print("Merging addresses...") df_adds = chunk.progress_apply(merge_addresses, axis = 1) [(chunk.append(df...
David M
1

votes
2

answer
40

Views

Using list comprehension to create a list with single elements when using zip function [duplicate]

This question already has an answer here: Transform “list of tuples” into a flat list or a matrix 9 answers I have been trying to shuffle a list in specific manner: def shuffle(card_deck): shuffled = list() deck_size = len(card_deck) // 2 lhand_deck = card_deck[0: deck_size] rhand_deck = card_d...
UbadahJ
1

votes
2

answer
32

Views

Create a column in dataframe using lambda based on another columns with non-null values

I have dataframe with movie titles and columns with genres. Such as movie with title 'One' is 'Action' and 'Vestern', because have '1' in appropriate columns. Movie Action Fantasy Vestern 0 One 1 0 1 1 Two 0 0 1 2 Three 1 1 0 My g...
Oysiyl
1

votes
2

answer
40

Views

Convert a nested for loop into a nested list comprehension [duplicate]

This question already has an answer here: What does “list comprehension” mean? How does it work and how can I use it? 4 answers I have a nested for loop but I can't for the life of me figure out how to transform it to a nested list comprehension. I don't seem to understand how nested list comps...
user3634589
1

votes
1

answer
61

Views

Python: is it possible to use list comprehension inside list declaration?

Let's say I have a list: t = ["3", "4", "5"] Is it possible to include this list into another using list comprehension? i.e.: t2 = ["1", "2", x for x in t, "6", "7"] with a result: ["1", "2", "3", "4", "5", "6", "7"]
agp22888
3

votes
4

answer
31

Views

for and in syntax explanation [duplicate]

This question already has an answer here: What does “list comprehension” mean? How does it work and how can I use it? 4 answers How to read aloud Python List Comprehensions? 2 answers I am using python 3, and I am looking over an example, but don't understand a part of the code that uses for a...
dshawn
13

votes
5

answer
790

Views

List comprehension iterating over two lists is not working as expected [duplicate]

This question already has an answer here: Nested list comprehension with two lists 5 answers I want to iterate over two lists. The first list contains some browser user-agents and the second list contains versions of those browsers. I want to filter out only those user-agents whose version is great...
Viktor
7

votes
5

answer
189

Views

List comprehension iterating over two lists is not working as expected

I want to iterate over two lists. The first list contains some browser user-agents and the second list contains versions of those browsers. I want to filter out only those user-agents whose version is greater than 60. Here is how my list comprehension looks: [link for ver in version for link in user...
Viktor
40

votes
1

answer
2.5k

Views

For loops with pandas - When should I care?

I am familiar with the concept of "vectorization", and how pandas employs vectorized techniques to speed up computation. Vectorized functions broadcast operations over the entire series or DataFrame to achieve speedups much greater than conventionally iterating over the data. However, I am quite su...
coldspeed
1

votes
1

answer
167

Views

Construct set with list comprehension via function call only if not None

Having the call set(self.oid_to_path(oid, entries_parents) for oid in modified_by_one_parent_oids) this works, but also adds None to the list if the function returns None So modifying it to set(self.oid_to_path(oid, entries_parents) for oid in modified_by_one_parent_oids if None != self.oid_to_path(...
Flavius
1

votes
2

answer
992

Views

python nested dict comprehension with tuple as key

I have a dict like so: { ('name', 'user1'): 'foo', ('user', 'user1'): 'bar', ('name', 'user2'): 'bat', ('user', 'user2'): 'baz' } and I would like to convert to: { 'user1': {'name': 'foo', 'user': 'bar'}, 'user2': {'name': 'bat', 'user': 'baz'} } I can do this with a default dict easily, but I woul...
rikAtee
1

votes
3

answer
867

Views

checking if combination already exists from list comprehension

As part of learning Python I have set myself some challenges to see the various ways of doing things. My current challenge is to create a list of pairs using list comprehension. Part one is to make a list of pairs where (x,y) must not be the same(x not equal y) and order matters((x,y) not equal (y,x...
RMDan
1

votes
2

answer
144

Views

Sum across all list positions in a dictionary

This is a question and answer I wanted to share, since I found it very useful. Suppose I have a dictionary accessible with different keys. And at each position of the dictionary I have a list of a fixed length: a={} a["hello"]=[2,3,4] a["bye"]=[0,10,100] a["goodbye"]=[2,5,50] I was interested to com...
lllllll
1

votes
1

answer
335

Views

Filtering out items from a list using nested list comprehensions in Python

I have two lists. One contains sentences, the other contains words. I want to have all the sentences, which do NOT contain any of the words from the list of words. I'm trying to achieve this with list comprehensions. Example: cleared_sentences = [sentence for sentence in sentences if banned_word for...
Phil
1

votes
1

answer
143

Views

Python unwanted UnicodeDecodeError exception from one entry in list comprehension

I am using Python 2.6 on Linux. I have a shift_jis (Japanese) encoded .csv file that I am loading. I am reading the header in, and doing a regex replacement to translate a few values, then writing the file back as shift_jis. I am hitting a UnicodeDecodeError on one of the characters in the file,...
frank
1

votes
3

answer
244

Views

How to extract from nested dictionaries using list comprehension

I'm trying to extract some data from XML. I'm using xmltodict to load the data into a dictionary, then using list comprehensions to pull out individual parts into separate lists. I will later be plotting these using matplotlib. XML: Hello This is an answer Hello A Different answer Yet another one M...
Andy Madge
1

votes
1

answer
228

Views

Write a list comprehension to a file

I generated a list of tupules using some function and list comprehension, like this [(x,y, func (x,y)) | x
ysakamoto
1

votes
4

answer
184

Views

Erlang list comprehension, once again

I'm trying to get a list comprehension working, which intention is to verify that each element X in List is followed by X+Incr (or an empty list). Later, I shall use that list and compare it with a list generated with lists:seq(From,To,Incr). The purpose is to practice writing test cases and finding...
Patrik Bäckström
1

votes
1

answer
401

Views

Tower of Hanoi-Haskell

I am really new using Haskell. I was trying to write an h4 function, which will calculate the minimum steps to finish the tower of Hanoi using 4 piles. I already got how to calculate it using 3 piles or h3. My main issue is using the list comprehension and returning the minimum value and also using...
user3349435
1

votes
4

answer
481

Views

list comprehension using regex conditional

i have a list of strings. If any of these strings has a 4-digit year, i want to truncate the string at the end of the year. Otherwise I leave the strings alone. I tried using: for x in my_strings: m=re.search("\D\d\d\d\d\D",x) if m: x=x[:m.end()] I also tried: my_strings=[x[:re.search("\D\...
Tim
1

votes
3

answer
306

Views

Creating a Python dictionary using a comprehension

I am trying to create a python dictionary with the following values in python 2.7.3: 'A':1 'B':2 'C':3 . . . . 'Z':26 using either of the following lines: theDict = {x:y for x in map(chr,range(65,91)) for y in range(1,27)} or theDict = {x:y for x in map(chr,range(65,91)) for y in list(range(1,27))}...
Skidooo
1

votes
2

answer
134

Views

list comprehension multiple and dependant levels

I would like to make a list comprehension with multiple for. To make it more difficult, I have dependencies between the two levels. The higher, app.containers is a list of containers, and it contains some contents, also iterable. This dictionary, at the end, should contain some pointers to the whole...
carrieje
1

votes
1

answer
86

Views

Print actual string found

I have this code which checks if a word from the list "Markers" can be found in the string "Translation". Translation= words.split("Translation:",1)[1] if any(x in Translation for x in Markers): print "found" How do i print the actual string that is found. I tried doing this Translation= words.spli...
user3078335
1

votes
2

answer
331

Views

How to get integers from list where sum of them is less than X?

Sorry for the mess that was here. I wanted a classic greedy algorithm for knapsack problem in haskell for integers. But there was other question - how to refer to list in list comprehension?
1

votes
1

answer
128

Views

Using pairs in list comprehension gives “redundant clause” warning

I get an odd-looking warning when I use the (_,_) pattern in a list comprehension. My minimal working example is as follows. theory Misc imports Main "~~/src/HOL/Library/Code_Target_Numeral" begin definition "xys = [(1::int,2::int),(2,3),(3,4)]" value "[x+4. (x,_) ← xys]" end Everything seems to...
John Wickerson
1

votes
1

answer
134

Views

Flatten doubly nested lists [duplicate]

This question already has an answer here: Flattening a shallow list in Python [duplicate] 23 answers How to convert this: [[[1,2,3], ['a','b','c']], [[4,5], ['d','e']], [[6,7,8,9], ['f','g','h','i']]] to this: [[1,2,3,4,5,6,7,8,9], ['a','b','c','d','e','f','g','h','i']] Knowing python, there must b...
Serbitar
1

votes
4

answer
70

Views

List comprehension or more efficient method for this code

I have the following code. For all lists inside a in the range 1, 4 that contain items, their length/ number of items is summed and then printed. a = [[1, 2, 3], None, [1.23, 4.56], ['a', 'b', 'c'], None, None] sum = 0 for i in a[1, 4): if a[i]: sum += len(i) print(sum) How could I simplify the mid...
1

votes
2

answer
1.2k

Views

Haskell - List comprehension accessing next element as well

I'm trying to use list comprehension to return the list elements that differ from the next. So far I've got it working with patterns and guards but ultimately need to use list comprehension So fn [4,3,3,1,1,3,3,3] and [4,3,1,3] would return [4,3,1] This is what I've got so far which just returns an...
bla9x
1

votes
2

answer
58

Views

How to get multiple element from one using list comprehension in Python?

My title may be not very clear and I apologize, it is not easy to explain. But an example will be more understandable. a = [1, 4, 7, 10] b = [x-1, x, x+1 for x in a] >> expected result: [0,1,2,3,4,5,6,7,8,9,10,11] Of course, it raises an error. Is it a way to use list comprehension in order to get t...
Delgan
1

votes
4

answer
46

Views

Given a string how to randomly transpose 2 of their letters?

Given a string: s = 'The quick brown fox jumps over the lazy dog' How can I randomly select a token, swap two letters from that token and return the string with the modified token? For example (*): The quick brown fxo jumps over the lazy dog In the above example the token fox was selected randomly a...
anon
1

votes
2

answer
209

Views

Sum nested key values of dict

This is my sample dictionary in Python 2.7: sample = {'T1': {'P1': 20, 'P2': 100}, 'T2': {'P1': 60, 'P2': 50}} I am trying to sum up all the values with the key 'P1' and 'P2' to get a result like this: reqResult = [80,150] How would I go about this? Many thanks.
endtask

View additional questions