Python lists comprehension [closed]

2024/11/20 16:22:49
string = "Hello 12345 World"
numbers = [x for x in string if x.isdigit()]
print numbers>> ['1', '2', '3', '4', '5']

Another example:

>>> noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
>>> primes = [x for x in range(2, 50) if x not in noprimes]
>>> print primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

What is confusing me is the x for x part. I've seen it a few places before but unsure what it means. Could someone provide more examples and explanation for these examples?

Answer

These constructs are called list comprehension.

Simple example

[x for x in iterable] literally means "for every element in iterable, add that element to newly created list" and is equivalent to

new_list = []
for x in iterable:new_list.append(x)

Line-by-line explanation:

Loop                             List comprehension
--------------------------------------------------------------------------
new_list = []                    [x for x in iterable]
for x in iterable:               [x for x in iterable]new_list.append(x)           [x for x in iterable]

A bit more complex example

[int(x) for x in string if x.isdigit()] can be read as "for every element in iterable, add the result of applying int to the element to newly created list if x.isdigit()".

Line-by-line explanation:

Loop                             List comprehension
-------------------------------------------------------------------------
numbers = []                     [int(x) for x in string if x.isdigit()]
for x in string:                 [int(x) for x in string if x.isdigit()]if x.isdigit():              [int(x) for x in string if x.isdigit()]numbers.append(int(x))   [int(x) for x in string if x.isdigit()]
https://en.xdnf.cn/q/120756.html

Related Q&A

Import everyday date for one year

Is there a simple way to import into my Python file a list with all the dates for a given year? What I need is to store everyday that a year has (01.01.2018----31.12.2018) into a list, so I can then i…

Object detection realtime using tensorflow

Im trying to detect objects in realtime using tensorflow. . I ran jupyter notebook in object_detection directory. then I opened the notebook file. It is firing the following errorIm getting the followi…

How do I get Python to read and extract words from a text file? [duplicate]

This question already has answers here:How to copy files(21 answers)Closed 7 years ago.So I need to make a code that opens a txt file, and then takes the content of that file and puts it into another t…

How to draw a checkered flag to the Python screen?

QUESTION: Implement the following pseudocode to draw a checkered flag to the screen.1. Ask the user for the size of the checkered flag (n). 2. Draw an n x n grid to the screen. 3. For i = 0,2,4,...,…

Open txt file in python

i need to open a txt file . In txt file i have Andrei:Popescu:Bucuresti Maria:Popescu:Targu-Mures ....How do I read a text file into three variable and for each line do something ? Sorry for my englis…

Python 3.3.3 time.sleep() error [duplicate]

This question already has answers here:Python: "global name time is not defined"(8 answers)Closed 10 years ago.Im getting the following error:The error:"Traceback (most recent call last)…

what is the decimal.getcontext().copy() mean [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

how do I change a python interpreter from english to my dialect

I have been stuck for months trying to edit the python interpreter (from www.python.org). All I want to do is to change the keywords eg. change from. English language: print() to Ibo language de().

Python, How to make a Video File(Mpeg/avi etc) into an exe?

First of all, I really dont know the correct direction on where to search or what to search.Going to the point of problems.How can I make my Video File into an exe format?I really need your help guys,…

Is it possible to avoid integers,floats and special characters using try-except statement only?

Im trying to make a code that allows only letters. I know we can do this using isalpha() method. But, Im looking for any other different solutions something like try-except?