Questions tagged [list-comprehension]

1

votes
1

answer
89

Views

Using for / list comprehension for creating a tuple from any amount of other tuples

With the following code I'm looking at how to create the TRACKS[0] and ARM[0] tuples (or even a whole set, e.g. ARM), as they are very similar - I think something like a list comprehension would work (as I'm picturing a for each loop). # MOTORS: all, m1, m2, m3, m4, m5 (+, -) MOTORS = ( ( (0b0101010...
zimchaa
1

votes
0

answer
57

Views

Is there an efficient way to get the count of object occurrence in another object list ? Django

In my Django app, I have a few models including, but not limited to: Vehicle, Vehicle Make, and Dealership. I create a list comprehension that creates JSON objects with the vehicle make, count of occurrences for that make in the Dealerships inventory, e.g. 6 Toyotas in their inventory, and the id of...
JBT
1

votes
4

answer
34

Views

Modify a list within a list, using map and lambda through list comprehension

Hi everyone I am new to Python and have been trying out how to create lists within lists containing multiples from 1 to 4, with each of them containing the same number of multiples as the number they are being multiplied with. In particular, applying the use of lambda and map function. [[0], [0, 2...
duetette_95
-2

votes
0

answer
22

Views

Python list comprehension with lambda function transformation

Suppose I have for simplicity this small corpus consisting of just 2 lines. 'This is first' 'This is second' In order to use it to my reduceByKey spark method I need to have the following output: [((u'This', u'is'), 1), ((u'is', u'first.'), 1), ((u'This', u'is'), 1), ((u'is', u'second.'), 1)] but wi...
Er1Hall
1

votes
2

answer
109

Views

List comprehension TypeError

The following list comprehension returns TypeError: 'in ' requires string as left operand, not list. new_list = [re.sub(r'in_content_1', r'in_content_2', i) for i in foo_list if re.findall(r'content_name', i, re.M) not in i] What is the correct way to use re.sub and conditioned re.findall in a list...
faber
1

votes
1

answer
43

Views

Python 3 : Time Difference : list comprehension of int VS list comprehension of list of int

I had a problem with computation time in list comprehension. While solving it i find that : In [209]: now = datetime.datetime.now() ...: for i in range(15): ...: k = [0 for j in range(100000)] ...: print(datetime.datetime.now() - now) ...: 0:00:00.004146 0:00:00.007886 0:00:00.011533 0:...
YnternetXplorer
1

votes
1

answer
147

Views

Using list comprehension to print converted string?

I have been trying to use list comprehension to simplify this code: c = 0 conv_regx = r'(Conv2d).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*?(\d+).*' for layer in list(cnn): if 'Conv2d' in str(layer): print(re.sub(conv_regx, r'\3 \2 \4 \5', str(layer))) c+=1 if c == len(layerList['C'])...
ProGamerGov
1

votes
3

answer
51

Views

Using the key, remove all keys with similar values

My goal is to have a random name of a fruit stored as fruit_name. Using this I would like to remove all fruits with the same first three letters in its value. For example: fruit_name = 'apple II' dictionary = {'grape' : 'abc.asrtyui', 'apple' : 'xyz7.qwertyui', 'apple I' : 'xyz.rghhyui', 'grape I...
John
1

votes
1

answer
52

Views

converting my long statement into list comprehension

Currently I have a statement like this that works great: if (l['key'] != '0') and (l['key'] != '') and (l['key'] != 'm3u8') and ('HIT' not in k['key']) : im new to list comprehension so instead of adding (l['key'] != 'something') each time I want to exclude extension I tried to do this: ext_group=['...
chowpay
1

votes
1

answer
36

Views

Why can't I fill sumcount in Counting Sort using list comprehension?

def countsort(alist): maxi=alist[0] for i in alist: if i>maxi: maxi=i indexlist=[i for i in range(0,maxi+1)] count=[alist.count(i) for i in indexlist] sumcount=[0 for i in range(0,maxi+1)] print(indexlist) print(count) sumcount=[count[i] if i==0 else count[i] + sumcount[i - 1] for i in range(0, len...
1

votes
2

answer
64

Views

Speeding up iterating over a range and comparing a value

I have this loop that generates a combination of numbers and solves to see if they equal a solution. After running a profiler I find that the sum and the comparison to the solution take the longest amount of time. Is this just due to the number of calls to each of them or would there be a way to mak...
zeetitan
1

votes
0

answer
56

Views

Separating nested for loops in list comprehensions

Starting from this dataframe import pandas as pd df2 = pd.DataFrame({'t': ['a', 'a', 'a', 'b', 'b', 'b'], 'x': [1.1, 2.2, 3.3, 1.1, 2.2, 3.3], 'y': [1.0, 2.0, 3.0, 2.0, 3.0, 4.0]}) it's possible to simplify these nested for loops: for t, df in df2.groupby('t'): print('t:', t) for d in df.to_dict(ori...
Vrokipal
1

votes
1

answer
56

Views

Changing a list value using a list comprehension in python

I have a nested list made up of 'x's and '.'s, with the boundaries represented by '-'. If there is a 'x', I have to change the '.' within the 3x3 square of the 'x' to a character such as '|'. I have working code, but I am wondering if and how I could use list comprehension on this problem instead?...
1

votes
1

answer
33

Views

Multiple list comprehensions from a single CSV file source

I'm trying to use list comprehensions to get specific columns from a CSV file source. Here's some code that simulates the CSV file data that I see: import pandas as pd import numpy as np # Setup of simulated data seconds = [1,2,3] values = [0.5,0.4,0.3] non_relevant_data = [8,6,7] nanos = [5757,67...
Tony A.
1

votes
2

answer
62

Views

List comprehension to find matching parens

I'm trying to come up with a list comprehension that will match open and close parens. So far I have these two statements which grab two lists of open and close parens separately my_str = 'hanz(and(franz/bob())+ 7) + tom(2)' Grab idx of open parens: [ i for i,c in enumerate(my_str) if c == '('] # [4...
darkpbj
1

votes
1

answer
54

Views

I Want to split list into two lists right_order[] and reverse_order[], while comparing items in list

I have result list where it has both ordered items like A, B and B, A combis or it can be 1,2 and 2,1 etc, if we found any reverse combis for A, B or 1,2 or 3211, 3222 or anything then reversed combis should store in target_list and correct ordered combis should store in source_list. also if we don...
smily dips
1

votes
1

answer
38

Views

execution order of expressions in a list comprehensions [duplicate]

This question already has an answer here: Understanding nested list comprehension 2 answers Given the following expressions: matrix = [[1,2,3],[4,5,6],[7,8,9]] A matrix is created, then a list comprehension is executed to create a flat list. The comprehension runs from left to right. flat = [x for...
dcrearer
1

votes
1

answer
44

Views

Using list comprehensions, transform all vowels within a string to upper case? [duplicate]

This question already has an answer here: python how to uppercase some characters in string 7 answers Thanks for your help Example byron = bYrOn This is an old homework I'm looking over.
A J E
1

votes
1

answer
52

Views

List Comprehensions to create pairwise dissimilarity

I'm not familiar with list comprehensions but I would like to compute the bray-curtis dissimilarity using list comprehensions. The dissimilarity is given by def bray(x): bray_diss = np.zeros((x.shape[0], x.shape[0])) for i in range(0, bray_diss.shape[0]): bray_diss[i,i] = 0 for j in range(i+1, bray_...
user1595929
1

votes
1

answer
128

Views

How to Prepare Text for Machine Learning pipeline with compiled Regular Expressions and/or List Comprehension?

I am trying to prepare text in a Python function for a machine learning pipeline and I am having trouble to get the correct output. So, I want to lowercase all words, replace symbols by spaces, delete symbols and remove stopwords from nltk. I tried all kinds of different approaches from list compreh...
J. Jones
1

votes
2

answer
60

Views

Putting a break in list comprehension

How can I get python to add a break in the middle of the list comprehension? The question is to take the list of RNA nucleotides and return a list of codons using list comprehension. I have the following code: import random bases=['U', 'A', 'C', 'G'] b1=[random.choice(bases) for i in bases [0:3] '\n...
user10613120
1

votes
1

answer
38

Views

Multiple Elifs based on Different Factors

I have a pands df with int columns year, month, and day. I would like to create a new column df.is_payday, in the most pythonic way possible, that is a 1 whenever df.day is 20 or 30, else 0. However, some months don't have 30 days, so in those cases I would like df.is_payday to have a 1 only when d...
Odisseo
1

votes
1

answer
14

Views

Compare 2 lists, based on index from 2 other lists, and save index in new list with list comprehension

So what I am trying to do is: 1) Find where list1[y] == list2[x] 2) Determine if list3[y] < (0.4 list4[x]) 3) If so, store the index y in a new list of indexes This loop works, however it takes almost a full minute to run with my data set. I want to know if I can do this with list comprehension. Th...
GitGud
1

votes
1

answer
41

Views

List comprehension with zipped iterators and conditionals

I have been trying to populate a list such that if another list containing a boolean at index j is True, I perform an operation(simple regex) on another list else choose to pass(implicitly). import re maskNan = [True, True, False, True, False] stringList = ['foo.abc','foo.def','foo.ghi','foo.jkl'] f...
CS101
1

votes
1

answer
39

Views

Error in list comprehension with `locals()` in python

I have run a python script that created multiple variables. Now I want to iterate over a few dataframes (created by the script) matching a specific pattern and perform simple operations on them. Initially I want to get the number of rows (with shape()) of each of the dataframes in list_dfs, as shown...
BCArg
1

votes
2

answer
57

Views

Syntax error while trying List comprehension in Python

I am getting a syntax error when trying to change the following code to List comprehension Initial Code: new_num =[] for num in a: if num in b: if num not in new_num: new_num.append(num) print(new_num) Change to List comprehension: new_num = [num for num in a if num in b if num not in new_num] prin...
johnny_linux
1

votes
1

answer
74

Views

When cleanig tokenized data, how to use .isalpha() in a list of lists to return values, not Booleans?

I'm practicing NLP with the nltk Library and I want to build myself an dataset for that. I combine several documents into a list of lists and then preprocess them. First I tokenize it, lowercase it and then I want to remove punctuation. It works for a vecor, but not for a list of lists: Example for...
Largo Terranova
1

votes
0

answer
119

Views

How to create meshgrid with non-integer stepsize of list elements?

I have 2 lists of x and y coordinate that are independently generated, with a/h amount of points between 0 and a. x = np.linspace(0, a, a/h) y = np.linspace(0, d, d/h) when a/h is such that 0 increases to a in steps of integers i.e. [0,1,2,..,a]. It's nice because then the number of elements within...
user3613025
1

votes
2

answer
27

Views

Escape a line inside a format function

I'm trying to use \n inside a format function in python, since it's not possible to do it using fstrings. But I'm not sure how it's done. raw_data = {'post 1': 'link 1', 'post 2': 'link 2'} data = [('Post:{}\nLink: {}').format(title, link) for title, link in raw_data.items()] print(data) Which print...
Psycoguana
1

votes
1

answer
40

Views

Understanding list comprehension that uses recursion

I am currently learning about list comprehension and come across this line of recursive code: ans = [sort(a, i + 1) for a in ans] I have tried substituting that line with the following: for a in ans: ans = (sort(a, i + 1)) Could somebody please help me understand where I have made a mistake? thanks!
Handsome Woman
1

votes
0

answer
44

Views

Select few Dictionary Keys from list of dictionaries while also adding new keys

i want to select few of the keys from the existing list of dictionary and also add few other keys by looking up into another map . main list is as follows result=[{'key1':123,'key2':'prod','key3':'abc','key4':'cde'},{'key1':123,'key2':'prod','key3':'def','key4':'qrs'},{'key1':321,'key2':'sale','key...
Rahul Samant
1

votes
2

answer
20

Views

Correct syntax of list comprehension for this nested loop?

I have a dataframe column, df['Traversal'], where each row may contain a string something like 'Paris->France->London'. The correct output works for the following code: emptylist = [] for x in df['Traversal']: for y in x.split('->'): emptylist.append(y) I've tried variations of: emptylist = [y.split...
hiimarksman
1

votes
1

answer
26

Views

Python List Comprehension with two cycles

I am a beginner in Python. I learn list comprehension but my code is bad, because list comprehensions are wrong or missing: I tried a lot of things, but results are generators or errors. Could you give me advice...? Thank you. Acer import itertools as it aT=list(it.permutations([4,3,3,0],3)) uT=list...
Acer1968
1

votes
3

answer
39

Views

list comprehension not evaluating as expected

I have the following list: z = [ [7,None], [9,None], [None,7], [None, 15], [None, None], [2,None], [0,None]] ..and wanted a list comprehension which will return the integer in the element if there is one even if it is 0 and and will return 1 for an element where both subelements are None. I br...
cardamom
1

votes
3

answer
851

Views

python list_comprehension to get multiple values

I want to do something like below. I want the output of the condition expression in a list comprehension. Is it possible with list comprehension? def why_bad(myvalue): #returns a list of reasons or an empty list it is good ... return [ reason1, reason2 ..] bad_values = [ (myvalue,reasons) for myvalu...
balki
1

votes
5

answer
136

Views

Python: Linking Lists Together

Suppose I have a list where each index is either a name, or a list of rooms the preceding name index reserved. [['Bob'],['125A, '154B', '643A'],['142C', '192B'], ['653G'], ['Carol'], ['95H', 123C'], ['David'], ['120G']] So in this case, Bob has the rooms: 125A, 154B, 643A, 152C, 192B, and 653G rese...
zhuyxn
1

votes
1

answer
186

Views

Condensing Python list of frequencies with duplicates (maybe with comprehensions)

I'm using Python to count the frequency of pixel colors in an image. The Python Imaging Library can convert an image to a list of RGB values, and from there I can easily count duplicates, ending up with a dictionary of pixel values (as strings) and frequencies, like so: { '255-255-255': 450, '255-25...
Chris Wilson
1

votes
1

answer
63

Views

Why nested list indexing gets swapped with list comprehensions?

I expected the following 2 code-segments to be essentially equivalent. return tuple(tuple( False if (i,j) in neighborhood else avail[i][j] for i in range(len(avail))) for j in range(len(avail[i]))) (False, False, True, True, True) (False, False, True, True, True) (False, False, True, True, True...
user1358
1

votes
1

answer
55

Views

Is this a bug that list comprehenstion leak a variable name in coffeescript?

While learning coffeescript I found that this: people = (''#{name}'' for name in ['Foo', 'Bar', 'Baz']) compile to this (function() { var name, people; people = (function() { var _i, _len, _ref, _results; _ref = ['Foo', 'Bar', 'Baz']; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++)...
jcubic
1

votes
4

answer
146

Views

Python List Comprehension. Generating a List by repeatedly calling a function till it returns a predefined value

I would like to generate a list by repeatedly calling a function till the function return a predefined value. myList = [i,r = foo() while i==0] myList = [r1, r2, r3, r4...] as long as returned i value is == 0 Is there a way to do this using list comprehension?
Pavan

View additional questions