Python🐍

python - list

2020-09-01  本文已影响0人  Pingouin

list

friends = ['xinlei', 'daidai', 'xiaren']
print(friends[0])

1. lists are mutable (changeable)

fruit = 'banana'
fruit[0] = 'b' # this will get an error because string doesn't support item assignment
lotto = [2,33,22,33,44]
lotto[2] = 28
print(lotto)

2. how long is a list

len()
#len() tells us the number of elements 

3. use the range function

print(range(4))
# [0,1,2,3]
friends = ['xinlei', 'daidai', 'xiaren']
print(len(friends))
print(range(len(friends)))
# 两种方法写loop
for i in range(len(friends)):
    friend = friends[i]
    print('Hi:', friend)
# 这种方法更好
for friend in friends:
    print('Hi:', friend)

4. concatenating lists using +

# we can create a new list by adding two existing lists together
a = [1,2,3]
b = [4,5,6]
c= a + b
print(c)
# [1,2,3,4,5,6]

5. lists can be sliced using :

t = [6,23,35,6,7,8]
t[1:3]
t[3:]
t[:]
# just like strings,  the second number is up to but not including 

6. list methods

x = list()
type(x)
dir(x)
# 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'

7. build a list from scratch

stuff = list() # construct emtpy list
stuff.append('book')
stuff.append(99)
print(stuff)

注意append 和 extend 区别: 列表可包含任何数据类型的元素,单个列表中的元素无须全为同一类型。 append 是将整个的对象添加到原列表的末尾。 而extend 是将列表与原有的列表合并。

8. is something in a list

some = ['ke', 1996, 2, 10, ['bdate']]
'ke' in some # T
['bdate'] in some # T

注意与string不同的是,list可以有list.index 但是没有find

9. lists are in order

friends = ['xinlei', 'daidai', 'xiaren']
friends.sort()
print(friends)

10.build-in functions and lists

list = [2,4,6,7,86,543]
print(len(list))
print(max(list))
print(min(list))
print(sum(list))
print(sum(list)/len(list)) # return to float

对比两种方法: 同样的output

#方法一 
total = 0
count = 0
while True:
    inp = input("enter a number:")
    if inp == 'done': break
    value = float(inp)
    total = total + value
    count +=1
average = total/count
print('average', average)
#方法二 用list
numlist = list()
while True:
    inp = input('input a number:')
    if inp == 'done': break
    value = float(inp)
    numlist.append(value)
average = sum(numlist)/len(numlist)
print('average',average)

11. best friends: strings and lists

abc = 'with three words'
stuff = abc.split()
print(stuff)
for w in stuff:
    print(w)
line = '1;2;3;line'
thing = line.split(';')
print(thing)
# 返回一个list

12. The double split pattern

example = 'from ke.zhang@ugent.be sat Jan 5 20:00:00 2020'
words = example.split() # words : ['from','ke.zhang@ugent.be','sat','Jan','5','20:00:00','2020']
email = words[1] #email: ke.zhang@ugent.be
school = email.split('@')
print(school[1])
上一篇 下一篇

猜你喜欢

热点阅读