python的切片,迭代,列表生成式

python的代码需要有优雅,明确,简单的特性。代表着需要代码越少越好,越简单越好。为此,python提供了许多高级特性,如切片,迭代,列表生成式等等,可以有效的用简单代码实现复杂功能。

参考资料:廖雪峰官方网站http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014317568446245b3e1c8837414168bcd2d485e553779e000

1,切片

适用类型:list, tuple, str

切片功能简单说就是实现截取,不管是列表list,不可变列表tuple还是字符串str,使用切片可以使代码更简单。

    (1)list

li = ['0', '1', '2', '3', '4', '5', '6']
print(li[1:3])
print(li[:2])
print(li[3:])
print(li[-5:-3])
print(li[-5:])
print(li[::2])

   结果为:

['1', '2']
['0', '1']
['3', '4', '5', '6']
['2', '3']
['2', '3', '4', '5', '6']
['0', '2', '4', '6']

    li[1:3] : 从list的索引1开始取,取到索引3停止,不包括索引3

    li[:2] : 从头取,取到索引2停止,不包括2

    li[3:] : 从索引3一直取到最后

    li[-5:-3] : 从索引-5取到索引-3,不包括索引-3

    li[-5:] : 从索引-5取到最后

    li[::2] : 从头取到尾,每2个元素取一个中间隔一个

 

    (2)tuple

    tuple本身就是一种list, 而它的切片操作与list切片操作相同,只是得到结果依然是不可变的tuple

tup = ('0', '1', '2', '3', '4', '5')
print(tup[2:])
print(tup[:4])
print(tup[1::3])

   结果为:

 ('2', '3', '4', '5')
 ('0', '1', '2', '3') 
 ('1', '4')

    (3)str

    str的切片操作是对每个字符的截取,其它与list和tuple切片相同

string = '012345'
print(string[2:])
print(string[:4])
print(string[1::3])

    结果为:

2345
0123
14

2,迭代

适用类型:list, tuple, str, dict

python中可迭代的类型为Iterable类型。比如list, tuple, str等

python的for循环抽象程度比较高,不光是列表list和tuple可以迭代,字符串和字典也可以。

    (1)list, tuple

li = ['zero', 'one', 'two', 'three', 'foul', 'five', 'six']
for value in li:
    print(value)

     结果为:

zero
one
two
three
foul
five
six

    类似于forEach,不能获取每次迭代的索引,只获取迭代数值

  

for index, value in enumerate(li):
    print(index, value)

     结果为:

0 zero
1 one
2 two
3 three
4 foul
5 five
6 six

    enumerate()函数可以把list变成索引-元素这种形式,从而可以在for循环中同时获取索引和数值

 

 

for index in range(len(li)):
    print(index, li[index])
# 同样可以获取上面的结果

    (2)dict

dic = {'one': 1, 'two': 2, "three": 3}
for key in dic:
    print(key)

       结果为:

two
three
one

    直接迭代字典,每次获取的元素是字典的key

for value in dic.values():
    print(value)
1
3
2

    迭代字典的所有数值,用来获取每次迭代的数值。

for key, value in dic.items():
    print(key, value)
one 1
three 3
two 2
for value in dic.items():
    print(value)
('two', 2)
('three', 3)
('one', 1)

    (3)str

    字符串的迭代迭代的是字符串的每一个字符

string = '012345'
for value in string:
    print(value)
0
1
2
3
4
5

  

 

3,列表生成式

使用类型:可以迭代的类型

列表生成式可以进一步简化代码。

 

列表生成式返回的是数组, for前面的表达式可以代替for中的return

a = [x * x * x for x in range(0, 11)]
print(a)

    得到0-10中每个数的立方所组成的数组

[0, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

  

b = [x * x * x for x in range(0, 11) if x % 2 == 0]
print(b)

    得到0-10中每个偶数的立方所组成的数组

[0, 8, 64, 216, 512, 1000]
a = [1, 2, 3, 4, 5, 6]
b = [4, 5]
c = [x * y for x in a if x % 2 == 0 for y in b]
print(c)

    可以得到a中的每个偶数和b中的每个数相乘的结果组成的数组

 [8, 10, 16, 20, 24, 30]
a = {'a': 'b', 'c': 'd', 'e': 'f'}
b = [key + value for key, value in a.items()]
print(b)

    可以得到字典a中每个元素的key与value相加的结果得到的数组

['ab', 'cd', 'ef']

猜你喜欢

转载自2914905399.iteye.com/blog/2319789
今日推荐