python创建一个一到二十五的列表

  • 生成一个连续数的列表
a = [y for y in range(1, 26)]  # 列表表达式
b = list(range(1, 26))  # 将range转换为list对象
c = []
for i in range(1, 26):
    c.append(i)
print(a)
print(b)
print(c)

运行结果:

PS A:\python_file> python -u "a:\python_file\project\practice\1.py"
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]

注意,如果写成print(a,"\n",b,"\n",c)就会出现下面这种情况列表前面多一个空格,原因是逗号在print中充当空格的作用:

PS A:\python_file> python -u "a:\python_file\project\practice\1.py"
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] 
 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
  • 如果要生成某种符合条件的列表
    条件:1到25中被2整除的数生成的列表
  • 方法一:
    使用列表表达式
a = [i for i in range(1, 26) if i % 2 == 0]
print(a)

运行结果:

PS A:\python_file> python -u "a:\python_file\project\practice\1.py"
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24]
  • 方法二:
    使用filter(function or None, iterable) --> filter object+三元表达式
    python创建一个一到二十五的列表_第1张图片
a = list(filter(lambda x: True if x % 2 == 0 else False, range(1, 26)))
print(a)

运行结果:

PS A:\python_file> python -u "a:\python_file\project\practice\1.py"
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24]
  • 扩展一:
    三元表达式
    a = "变量一" if 条件 else "变量二" # 意义:如果满足条件那么a=变量一,否则等于变量二
  • 扩展二:
    列表表达式进阶,看这篇文章:
    https://blog.csdn.net/mjfppxx/article/details/113992427

你可能感兴趣的:(python)