python中强大的for用法

#!/usr/local/bin/python3
# -*- coding: UTF-8 -*-

##1.遍历

#遍历字符串
s = 'I love you'
    for i in s:
        print(i)

print('\n')
#遍历列表

l = ['y', 'l', 'b']
    for i in l:
  print(i)

print('\n')
#通过enumerate获得下标和val
for i, v in enumerate(l):
    print(i, v)
print('\n')

#遍历字典:
d = {'a': 'apple', "b": "blanan", "c": "car"}
#以下三种写法输出一样
for i in d:
    print(i, d.get(i))
for k, v in d.items():
    print(k, v)
for k, v in dict.items(d):
    print(k, v)
print('\n')

##2.列表生成
print(range(10))
print(range(0, 10))
for i in range(10):
    print(i)
print('\n')

#强制转换为列表
print(list(range(1, 11)))
print([i for i in range(1, 11)])
print([i * 3 for i in range(1, 11)])
print([str(i) for i in range(1, 11)])
print([i for i in range(1, 11) if i % 2 == 0])

print('\n')

#实现冒泡排序
l = [1, 12, 4, 2, 0, 8, 3, 7]
n = len(l)

for i in range(n - 1):
    for j in range(i + 1, n):
        if l[i] > l[j]:
            l[i], l[j] = l[j], l[i]
print(l)
 
输出:

 

#初始化一个5行4列的二维列表

line = 5
column = 4
dp = [[0] * (column) for _ in range(line)]
print(dp)

 

 

posted on 2020-07-01 12:05  Ryanyanglibin  阅读(1241)  评论(0编辑  收藏  举报

导航