10月 282020
 
# -*- coding:utf-8 -*-
# 列表推导式 == 列表解析式
# list = [ item for item in iterable ]
# iterate:迭代
# 放在列表中的元素,就是后面循环的元素本身

a = [i ** 2 for i in range(1, 10)]  # 将1-9的平方值依次放入列表
c = [j + 1 for j in range(1, 10)]  # 将1-9分别加1的值放入列表
k = [n for n in range(1, 10) if n % 2 == 0]  # 依次判断1-10中是否为偶数并将偶数值放入列表
z = [letter.lower() for letter in 'ABCEDFGHIJKLMN']  # 将字符串中的大写字母依次转换为小写并放入列表
print(a, c, k, z)

# 字典推导式
d = {i: i+1 for i in range(4)}  # 将0-3依次作为key,0-3分别加1作为value,放入字典
print(d)
g = {i: j for i, j in zip(range(1, 6), 'abcde')}  # 将1-5依次作为key,将字符串中字符依次作为value,放入字典
print(g)
m = {i: j.upper() for i, j in zip(range(1, 6), 'abcde')}  # 将1-5依次作为key,将字符依次作为value并转换大小,放入字典
print(m)

# enumerate:枚举
# 循环列表时获取元素的索引
# 列表是有序的
# enumerate()函数,参数为可迭代对象,返回一个枚举对象。
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
for num, letter in enumerate(letters):  # 返回一个包含计数值(默认从0开始)和通过迭代获得的值
    print(letter, 'is', num + 1)

# 示例
print(list(enumerate(letters)))
print(list(enumerate(letters, start=1)))
C:\Users\harveymei\PycharmProjects\mod3736\venv\Scripts\python.exe C:/Users/harveymei/PycharmProjects/mod3736/news.py
[1, 4, 9, 16, 25, 36, 49, 64, 81] [2, 3, 4, 5, 6, 7, 8, 9, 10] [2, 4, 6, 8] ['a', 'b', 'c', 'e', 'd', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
{0: 1, 1: 2, 2: 3, 3: 4}
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
{1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E'}
a is 1
b is 2
c is 3
d is 4
e is 5
f is 6
g is 7
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g')]
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f'), (7, 'g')]

Process finished with exit code 0

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据