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
Related
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.
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 3 years ago.
input_list = [22,456,3465,456,6543,546,345]
for num in input_list:
if num==0 or num%2==0:
input_list.remove(num)
Could you please tell me what is the problem in this code?
It is not removing second 456 from the list.
The problem with your code is that you are removing an item while iterating over the list.
So when the num become 22 then 22 will be removed and 456 become index 0 in your list, in the next iteration the for loop looks for index 1 which is 3465.
Try this:
input_list = [i for i in input_list if i%2 == 1]
This question already has answers here:
How to convert list to string [duplicate]
(3 answers)
Closed 3 years ago.
I have this list:
x = ['nm0000131', 'nm0000432', 'nm0000163']
And I would like to convert it to:
'nm0000131',
'nm0000432',
'nm0000163'
e.g: I would like convert a list of strings (x) to 3 independent strings.
If you want three separate string you can use for loop.
Try the following code:
x = ['nm0000131', 'nm0000432', 'nm0000163']
for value in x:
print(value)
Output will be like:
nm0000131
nm0000432
nm0000163
The following code will display an output like "nm0000131" ,"nm0000432" ,"nm0000163":
x = ['nm0000131', 'nm0000432', 'nm0000163']
str1 = '" ,"'.join(x)
x = '"'+str1+'"'
print(x)
As you mentioned in the comment I would like to include some more points to my answer.
If you want to get the key-value pairs then try the following code.
y = {'131': 'a', '432': 'b', '163': 'c'}
w = []
for key, value in y.items():
w.append(value)
print(w)
Output:
['c', 'a', 'b']
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))
This question already has answers here:
Outerzip / zip longest function (with multiple fill values)
(3 answers)
Closed 5 years ago.
I need to zip two lists inclusively. I.e. keep values of the longer list and, possibly, add a default value for the shorter one:
e.g.
lst_a = [1,2,3] # len = 3
lst_b = [5,6,7,8] # len = 4
# no default values
inclusive_zip(lst_a, lst_b) = [(1,5),(5,6),(3,7),(None,8)]
# with default value (e.g. for position in 2D space)
inclusive_zip(lst_a, 0, lst_b, 0) = [(1,5),(5,6),(3,7),(0,8)]
I can make something of my own, but was wondering if there's a built-in or super simple solution.
itertools.zip_longest(*iterables, fillvalue=None)
import itertools
def add_by_zip(p1,p2):
p_out = [a+b for a,b in itertools.zip_longest(p1,p2, fillvalue=0)]
print(p_out)