Python:for循环

1、遍历列表

diseases = ['HUA', 'T2DM', 'HBP']
for disease in diseases:
    print(disease)

# 输出:
HUA
T2DM
HBP

2、遍历字典

person = {'name': 'Alice', 
          'age': 25, 
          'city': 'New York'}

"""遍历字典的键和值"""
for key, value in person.items():
    print(key, ':', value)
# 输出:
name : Alice
age : 25
city : New York


"""只遍历字典的键"""
for key in person:
    print(key)
# 输出:
name
age
city

"""只遍历字典的值"""
for value in person.values():
    print(value)
# 输出:
Alice
25
New York

3、生成新列表

today = [1,2,3,4,5] 
future = [x**2 for x in today] # future为[1, 4, 9, 16, 25]

你可能感兴趣的:(Python基础,python)