将两个列表中不相等的元素组合起来的不同写法:
list_1 = [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
print(list_1)
等价于:
list _1 = []
for x in [1,2,3]:
for y in [3,1,4]:
if x != y:
list _1.append((x, y))
print(list_1)
注意:
一些例子:
from math import pi
vec = [-4, -2, 0, 2, 4]
list_1 = [x * 2 for x in vec] # 条件:x * 2
list_2 = [x for x in vec if x >= 0] # 条件:x >= 0
list_3 = [abs(x) for x in vec] # x的绝对值,即abs(x)
print("list_1 =", list_1)
print("list_2 =", list_2)
print("list_3 =", list_3)
freshfruit = [' banana', ' loganberry ', 'passion fruit ']
list_4 = [weapon.strip() for weapon in freshfruit]
# str.strip():省略字符串头部和尾部的空格,不能省略中间的空格
print("list_4 =", list_4)
list_5 = [(x, x**2) for x in range(6)] # 列表嵌套元组
print("list_5 =", list_5)
list_6 = [str(round(pi, i)) for i in range(1, 6)]
print("list_6 =", list_6)
'''
round()函数是一个四舍五入的函数,但是有坑,具体看这两个链接:
https://www.runoob.com/python/func-number-round.html
https://www.runoob.com/w3cnote/python-round-func-note.html
'''