首页 > 编程语言 >List comprehensions in Python

List comprehensions in Python

时间:2023-03-13 20:44:33浏览次数:46  
标签:even zip Python List list range comprehensions print

Reprinted from: note.nkmk.me-List comprehensions in Python

In Python, you can create a new list using list comprehensions. It's simpler than using the for loop.

This article describes the following contents.

  • Basics of list comprehensions
  • List comprehensions with if
  • List comprehensions with conditional expressions (like if else)
  • List comprehensions with zip(), enumerate()
  • Nested list comprehensions
  • Set comprehensions
  • Dictionary comprehensions
  • Generator expression

See the following article for examples of using list comprehensions.

Basics of list comprehensions

List comprehensions are written as follows:

[expression for variable_name in iterable]

Each element of iterable, such as a list or a tuple, is taken out as variable_name and evaluated with expression. A new list is created with the result evaluated by expression as an element.

An example of list comprehensions is shown with an equivalent for statement.

squares = [i**2 for i in range(5)]
print(squares)
# [0, 1, 4, 9, 16]
squares = []
for i in range(5):
    squares.append(i**2)

print(squares)
# [0, 1, 4, 9, 16]

Although map() can do the same thing, list comprehension is preferred for simplicity and clarity.

List comprehensions with if

In list comprehensions, if can be used as follows:

[expression for variable_name in iterable if condition]

Only elements of iterable that are True for condition are evaluated with expression. Elements of iterable that are False for condition are not included in the list of results.

odds = [i for i in range(10) if i % 2 == 1]
print(odds)
# [1, 3, 5, 7, 9]
odds = []
for i in range(10):
    if i % 2 == 1:
        odds.append(i)

print(odds)
# [1, 3, 5, 7, 9]

Although filter() can do the same thing, list comprehension is preferred for simplicity and clarity.

List comprehensions with conditional expressions (like if else)

In the above example, elements that do not meet condition are excluded from the new list.

If you want to apply another operation to elements that do not meet condition like if else, use conditional expressions.

In Python, conditional expressions can be written as follows:

X if condition else Y

X is value or expression for True, and Y is value or expression for False.

You can use it for the expression part of list comprehensions:

odd_even = ['odd' if i % 2 == 1 else 'even' for i in range(10)]
print(odd_even)
# ['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']
odd_even = []
for i in range(10):
    if i % 2 == 1:
        odd_even.append('odd')
    else:
        odd_even.append('even')

print(odd_even)
# ['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']

It is also possible to apply different operations to the original element depending on the condition as follows:

odd10 = [i * 10 if i % 2 == 1 else i for i in range(10)]
print(odd10)
# [0, 10, 2, 30, 4, 50, 6, 70, 8, 90]

List comprehensions with zip(), enumerate()

In the for statement, zip() and enumerate() are often used. zip() aggregates elements from multiple iterables and enumerate() returns a value and its index.

Of course, you can also use zip() and enumerate() in list comprehensions.

List comprehensions with zip():

l_str1 = ['a', 'b', 'c']
l_str2 = ['x', 'y', 'z']

l_zip = [(s1, s2) for s1, s2 in zip(l_str1, l_str2)]
print(l_zip)
# [('a', 'x'), ('b', 'y'), ('c', 'z')]
l_zip = []
for s1, s2 in zip(l_str1, l_str2):
    l_zip.append((s1, s2))

print(l_zip)
# [('a', 'x'), ('b', 'y'), ('c', 'z')]

List comprehensions with enumerate():

l_enu = [(i, s) for i, s in enumerate(l_str1)]
print(l_enu)
# [(0, 'a'), (1, 'b'), (2, 'c')]
l_enu = []
for i, s in enumerate(l_str1):
    l_enu.append((i, s))

print(l_enu)
# [(0, 'a'), (1, 'b'), (2, 'c')]

You can also use if.

l_zip_if = [(s1, s2) for s1, s2 in zip(l_str1, l_str2) if s1 != 'b']
print(l_zip_if)
# [('a', 'x'), ('c', 'z')]

It is also possible to calculate a new value using each element.

l_int1 = [1, 2, 3]
l_int2 = [10, 20, 30]

l_sub = [i2 - i1 for i1, i2 in zip(l_int1, l_int2)]
print(l_sub)
[9, 18, 27]

Nested list comprehensions

List comprehensions can be nested just as for loops are nested.

[expression for variable_name1 in iterable1
    for variable_name2 in iterable2
        for variable_name3 in iterable3 ... ]

Line breaks and indentation are added for convenience, but they are not required.

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

flat = [x for row in matrix for x in row]
print(flat)
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
flat = []
for row in matrix:
    for x in row:
        flat.append(x)

print(flat)
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

Another example:

cells = [(row, col) for row in range(3) for col in range(2)]
print(cells)
# [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]

You can also use if.

cells = [(row, col) for row in range(3)
         for col in range(2) if col == row]
print(cells)
# [(0, 0), (1, 1)]
cells = [(row, col) for row in range(3) if row % 2 == 0
         for col in range(2) if col % 2 == 0]
print(cells)
# [(0, 0), (2, 0)]

Set comprehensions

If you change the square brackets [] in the list comprehension to the curly braces {}, a set (set type object) is created.

{expression for variable_name in iterable}
s = {i**2 for i in range(5)}

print(s)
# {0, 1, 4, 9, 16}

Dictionary comprehensions

Dictionaries (dict type objects) can also be created with dictionary comprehensions.

Use {} and specify the key and the value in the expression part as key: value.

Any value or expression can be specified for key and value.

l = ['Alice', 'Bob', 'Charlie']

d = {s: len(s) for s in l}
print(d)
# {'Alice': 5, 'Bob': 3, 'Charlie': 7}

Use the zip() function to create a new dictionary from each list of keys and values.

keys = ['k1', 'k2', 'k3']
values = [1, 2, 3]

d = {k: v for k, v in zip(keys, values)}
print(d)
# {'k1': 1, 'k2': 2, 'k3': 3}

Generator expressions

If the square bracket [] in the list comprehension is changed to the parenthesis (), the generator is returned instead of the tuple. This is called a generator expression.

List comprehension:

l = [i**2 for i in range(5)]

print(l)
# [0, 1, 4, 9, 16]

print(type(l))
# <class 'list'>

Generator expression:

print() does not output the generator elements. You can get elements by using the for statement.

g = (i**2 for i in range(5))

print(g)
# <generator object <genexpr> at 0x10af944f8>

print(type(g))
# <class 'generator'>

for i in g:
    print(i)
# 0
# 1
# 4
# 9
# 16

It is possible to use if and nest with generator expressions as well as list comprehensions.

g_cells = ((row, col) for row in range(0, 3)
           for col in range(0, 2) if col == row)

print(type(g_cells))
# <class 'generator'>

for i in g_cells:
    print(i)
# (0, 0)
# (1, 1)

For example, if a list with many elements is created with list comprehensions and used in the for loop, list comprehensions create a list containing all elements at first.

On the other hand, generator expressions create elements one by one after each loop, so the memory usage can be reduced.

You can omit the parentheses () if the generator expression is the only argument passed to the function.

 print(sum([i**2 for i in range(5)]))
# 30

print(sum((i**2 for i in range(5))))
# 30

print(sum(i**2 for i in range(5)))
# 30
```

There are no tuple comprehensions, but it is possible to create tuples by passing the generator expression to `tuple()`.

```python
t = tuple(i**2 for i in range(5))

print(t)
# (0, 1, 4, 9, 16)

print(type(t))
# <class 'tuple'>
```

标签:even,zip,Python,List,list,range,comprehensions,print
From: https://www.cnblogs.com/lfri/p/17212796.html

相关文章

  • python中os模块
    1.os.name   #  获取操作系统类型,如果是posix,说明系统是Linux、Unix或MacOSX,如果是nt,就是Windows系统2.os.uname #  要获取详细的系统信息,可以调用uname()......
  • python85 路飞项目 文件存储、搜索导航栏、搜索接口、搜索页面、支付宝支付介绍、支
    文件存储#视频文件,存储到某个位置,如果放在自己服务器上放在项目的media文件夹服务器上线后,用户既要访问接口,又要看视频,都是一个域名和端口分开:文件单......
  • Python Yolo V8 训练自己的数据集
    前期准备工作需要使用到的库,需要训练的素材一份图片或者视频importultralytics#YoloV8本体importlableimg#图片标注工具接着新建一份工作目录如下---data......
  • Java三大集合类 - List
    ListSetMap一、List几个小问题:1、接口可以被继承吗?(可以)2、接口可以被多个类实现吗?(可以)3、以下两种写法有什么区别?//Listlist1=newList();是错误的因为List()是......
  • python编程初体验1
    实验1源代码:1#实验123#task1_1.py45#print输出的几种方法6#用法1输出单个字符串或单个变量7print('hey,u')89#用法2:用于输出多个数据项,用逗......
  • 【ChatGPT解答】python 如何判断某个方法是继承于哪个父类
    ME:python如何判断某个方法是继承于哪个父类?给个能直接用的示例,能够自动遍历多层父类GPT:在Python中,可以通过使用内置函数inspect.getmro()来获取一个类的方法解......
  • Python strip()方法
    描述Pythonstrip()方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。语法strip()方......
  • 什么是 Python 类的继承和多继承?
    本文首发自「慕课网」,想了解更多IT干货内容,程序员圈内热闻,欢迎关注!作者|慕课网精英讲师朱广蔚在面向对象的程序设计中,定义一个新的class的时候,可以从某个现有的class......
  • Python中[-1]、[:-1]、[::-1]、[n::-1]、[:,:,0]、[…,0]、[…,::-1] 的理解
    在python中会出现[-1]、[:-1]、[::-1]、[n::-1]、[:,:,0]、[…,0]、[…,::-1],他们分别是什么意思呢,这里就来详尽的说一下:下面的a=[1,2,3,4,5][-1]:列表最后一项[:-1]......
  • python开发环境使用和编程初体验
    #实验任务1 print('hey,u')print('hey','u')x,y,z=1,2,3print(x,y,z) print('x=%d,y=%d,z=%d'%(x,y,z)) print('x={},y={},z......