how to analyze the logic of func RANGE in python? [duplicate] - python-3.x

This question already has answers here:
The order of nested list comprehension and nested generator expression in python
(5 answers)
Explanation of how nested list comprehension works?
(11 answers)
Closed 1 year ago.
I am still confused those sentence after I run them, I mean how do they execute step by step, someone can give some suggestions?
print([j for i in range (10) for j in range (5)])
print([[j for i in range (10)] for j in range (5)])
print([j for i in range (10) for j in range (5) for k in range(3)])

Largely, list comprehensions are concise for loops. Sometimes they can be difficult to understand and for that reason, I would suggest converting the list comprehension into a for loop for understanding.
print([j for i in range(10) for j in range(5)])
Is the same as:
result = []
for i in range(10):
for j in range(5):
result.append(j)
The others are very similar, can you try and convert them to for loops?
Hint (2): The second one has a nested list, so you'll need to initialize another list and append that list to the main list, result.
Hint (3): The last list comprehension has another nested for loop with another variable k.

Related

for loop doesn't itterate through all the data? [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 1 year ago.
data = [1, 2, 3, 4, 5]
for x in data:
print(x)
if data.count(x) < 2:
data.remove(x)
Hello Guys,
so I am currently working through py.checkio.org and am at a point where I have to remove all the numbers that are unique in a list.
When I run my code without the if statement I get an output counting from 1 to 5. But once I run the for loop with the if statement the for loop only runs through the data for every second number and my output is 1 3 5. Can anyone please tell me what is happening here?
While the from #Stef and #0x5453 are both relevant to your problem. The comment from #ConnorTJ is patently wrong. The remove function does not remove the item at the index but the first occurrence of the item.
To answer your question, about what's going on here, let[s examine your code:
The first pass through the value of x is 1
You print the value of x
You then test to see if the number of occurrences of x is less than 2
Since the answer is yes, you proceed to remove the item from the list.
The second pass through the list the For loop picks up the next value in the list (at index 1) which is now the value 3
You print the value 3
You check to see if the count of 3 is less than 2
Since the count is less you remove that item from the list.
This process than continues
Simple solution, use filter()
Construct an iterator from those elements of iterable for which function returns true
it returns a list of the list items that the function returned true for.
example:
x = [1,1,2,2,3,4]
x = filter(lambda f: (x.count(f)<2), x)
x = list(x)
print(x)
or in short: print(list(filter(lambda f: (x.count(f)>=2),x)))
output is [1,1,2,2]

For-loop skipping a term when searching for list of substrings within a list of strings [duplicate]

This question already has answers here:
Python list.remove() skips next element in list
(6 answers)
Closed 1 year ago.
I need to remove from my_list anything that contains any substring from banned (both lists are very long, approximately 30k+).
Here's a mini example:
my_list = ['dnb','distinctive_group_inc','real-estate-profile','estate.com']
banned = ['distinctive','estate']
Desired outcome:
my_list = ['dnb']
I'd like to be able to do it in one go so I tried:
my_list = [i for i in banned if i not in my_list]
Since that didn't work at all, I tried it in two steps:
for i in reversed(my_list):
for j in banned:
if j in i:
my_list.remove(i)
else:
pass
How can I do it in one step?
If you like list comprehension (and I do), then you were on the right track. This takes your starting comprehension but changes the criteria slightly to to exclude words that have any partial match in the banned list.
my_list = ['dnb','distinctive_group_inc','real-estate-profile','estate.com']
banned = ['distinctive','estate']
my_new_list = [
word for word in my_list
if not any(banned_word in word for banned_word in banned)
]
print(my_new_list)
Should result in:
['dnb']

Python 3: how to re-order sublists of nested list? [duplicate]

This question already has answers here:
Transpose list of lists
(14 answers)
Closed 2 years ago.
I have the following nested list, and the number of sublist in the list:
l1 = [[['a','c','d'],['e','f','g'],[['a','b'],'d','1']], [['2','3','4'],['3','4','4'],[['1','2'],'3','4']], [['q1','3e','2e'],['r4','tt','t5'],[['t4','g4'],'r4','45g']]]
nb_sub = 3
I want to re-order the sublists by 'index', so the 1st sublist of each sublist, then 2nd sublist of each sublist, etc. The ouput I want is:
output = [[['a','c','d'],['2','3','4'],['q1','3e','2e']], [['e','f','g'],['3','4','4'],['r4','tt','t5']], [[['a','b'],'d','1'],[['1','2'],'3','4'],[['t4','g4'],'r4','45g']]]
zip seems to be the perfect tool for the job:
output = [x for x in zip(*l1)]

Looping columns [duplicate]

This question already has answers here:
Printing using list comprehension
(14 answers)
List comprehensions leak their loop variable in Python2: how making it be compatible with Python3
(2 answers)
Do variables defined inside list comprehensions leak into the enclosing scope? [duplicate]
(1 answer)
List comprehension rebinds names even after scope of comprehension. Is this right?
(6 answers)
Closed 4 years ago.
I'm amazed, maybe someone can explain what's happening....
When I run this very simple example:
df = pd.DataFrame(columns=['A','B','C'])
results = pd.DataFrame(columns=df.columns)
for i, col in enumerate(df):
print('.....'+col)
result = [print(col) for i in range(2)]
The result is (col is unknown the 1st time):
.....A
A
A
.....B
A
A
.....C
A
A
But what I really expected is:
.....A
A
A
.....B
B
B
.....C
C
C
What is happening??
I just ran:
import pandas as pd
df = pd.DataFrame(columns=['A','B','C'])
results = pd.DataFrame(columns=df.columns)
for i, col in enumerate(df):
print('.....'+col)
result = [print(col) for i in range(2)]
and it returned:
Out[]:
..A
A
A
..B
B
B
..C
C
C
Python 3.6.5
Pandas 0.20.3

range() returns the word itself [duplicate]

This question already has answers here:
Python 3 turn range to a list
(9 answers)
Closed 5 years ago.
I'm using python 3.6
when I use the range function in Python console, it didn't return an array, instead it shows the wording itself:
range(1, 5)
range(1,5)
print(range(1,5))
range(1,5)
How can I show the array?
The range() function in Python 3 returns an iterator, something you can iterate on, so you can use it as:
for x in range(1, 5):
print(x)
This iterator returns one value at a time, so it can be more memory efficient.
If you want to get a list, you can use this code:
list(range(1,3))

Resources