列表

2018-05-08  本文已影响4人  _大_兵_
>>> ["cat",3.1415,True,None,42]
["cat",3.1415,Ture,None,42]
>>> spam = ["cat","bat",3.14,True]
>>> spam[0]
"cat"
>>> spam[1]
"bat"
>>> spam[3]
True
>>> spam[-1]
True
>>>spam[-2]
3.14
>>> spam = ['cat','bat','rat','elephant']
>>> spam[0:4]
['cat','bat','rat','elephant']
>>> spam[1:3]
['bat','rat']
>>> spam = ['cat','dog','moose']
>>> len(spam)
3
>>> spam = ['cat','bat','rat','elephant']
>>> spam[0] = 'dog'
>>> spam
['dog','bat','rat','elephant']
>>> [1,2,3] + [4,5,6]
[1,2,3,4,5,6,]
>>> [1,2,3] *3
[1,2,3,1,2,3,1,2,3,]
>>> spam = ['cat','bat','rat','elephant']
>>> del spam[1]
>>> spam
['cat','rat','elephant']
cat_name1 = 'pooka'
cat_name2 = 'simon'
cat_name3 = 'zophie'
cat_name4 = 'miss cleo'
print('Ener the name of cat 1:')
cat_name1 = input()
print('Ener the name of cat 2:')
cat_name2 = input()
print('Ener the name of cat 3:')
cat_name3 = input()
print('The cat names are:')
print(cat_name1 + ' ' + cat_name2 + ' ' + cat_name3)

其实不必创建多个重复的变量,可以使用单个变量,包含一个列表值。下面改进上面的程序,使用列表可以保存用户输入的任意多的猫。

cat_names = []
while True:
    print('Enter the name of cat ' + str(len(cat_names)+1) + '(Or enter nothing to stop.):')
    name = input()
    if name == '':
        break
    cat_names.append(name)
print('The cat names are:')
for name in cat_names:
    print(' ' + name)

使用列表的好处在于,数据放在一个结构中,程序能更灵活的处理数据,比放在一些复杂的变量中方便。

supplies = ['pens','staplers','flame','binders']
for i in range(len(supplies)):
    print('Index ' + str(i) + ' in supplies is:' + supplies[i])
numbers = [1,7,3,2,5,6,2,3,4,1,5]
new_numbers = []
for x in numbers:
    if x not in new_numbers:
       new_numbers.append(x)
print(new_numbers)
# 单项赋值
cat = ['fat','black','loud']
size = cat[0]
color = cat[1]
disposition = cat[2]
# 多重赋值
cat = ['fat','black','loud']
size,color,disposition = cat

多重赋值,变量的数目和列表的长度必须严格相等。

spam += 1  等价 spam = spam + 1
spam -= 1   等价 spam = spam - 1
spam *= 1   等价 spam = spam * 1
spam /= 1   等价 spam = spam / 1
spam %= 1  等价 spam = spam % 1
1.index()返回元素在列表中的下标
2.append()将参数添加到列表的末尾
3.insert()第一个参数是新值的下标,第二参数是要插入的新值
4.remove()方法传入一个值,它将从被调用的列表中删除。如果该值在列表中出现多次,只有第一次出现的值会被删除。
5.sort()将列表中的值排序(当场排序),默认顺序:
  数字按照从小到大;
  字符串使用“ASCLL字符顺序”,而不是实际的字典顺序,这意味着大写字母排在小写字母前;
  既有数字又有字符串值的列表排序会报错。

  指定reverse关键字参数为Ture让sort()按逆序排列;例如 sapm.sort(reverse=Ture)
  如果需要按照普通的字典顺序排序,在sort()方法调用时,将关键字参数key设置为str.lower。例如: spam.sort(key=str.lower)将所有的表项当成小写,不会改变列表中的值。
>>> type(('hello',))
<class 'tuple'>
>>> type(('hello'))
<class 'str'>

type(),输出括号内的数据类型

>>> tuple(['cat','dog',5])
('cat','dog',5)
>>> list(('cat','dog',5))
['cat','dog',5]
>>> spam = [1,2,3,4,4]
>>> cheese = spam
>>> cheese[1] = 'hello'
>>> spam
[1,'hello',3,4,4]
>>> cheese
[1,'hello',3,4,4]

变量保存可变数据类型的值时,例如列表或字典,python就使用引用。对于不可变的数据类型的值,例如字符串、整型或元组,python变量就保存值本身。

>>> import copy
>>> spam = ['A','B','C','D']
>>> cheese = copy.copy(spam)
>>> cheese[1] = 42
>>> spam
['A','B','C','D']
>>> cheese
['A',42,'C','D']

如果要赋值的列表包含了列表,则使用deepcopy()函数代替。该函数将同事复制他们内部的列表。

上一篇 下一篇

猜你喜欢

热点阅读