#########################列表####################
1,列表的定义:
# 定义一个空列表
li = []
# 定义一个包含元素的列表,元素可以是任意类型,包括数值类型,列表,字符串等均可。
li = ["fentiao", 5,"male"]
*******列表是可变类型的序列,而元组与字符串是不可变类型的序列
2,#####列表的索引
In [3]: li[1]
Out[3]: 5
3,####列表的添加:
1)insert
In [5]: li.insert(0,'hello')
In [6]: li
Out[6]: ['hello', 'fentiao', 5, 'male']
2)append
In [10]: li.append('haah')
In [11]: li
Out[11]: ['hello', 'fentiao', 5, 'male', 'haah']
3)extend
In [14]: li.extend('hel')
In [15]: li
Out[15]: ['hello', 'fentiao', 5, 'male', 'haah', 'h', 'e', 'l']
In [16]: li.extend(['hak','python'])
In [17]: li
Out[17]: ['hello', 'fentiao', 5, 'male', 'haah', 'h', 'e', 'l', 'hak','python']
4,列表的删除:
1)具体子段
In [21]: li.remove("fentiao")
In [22]: li
Out[22]: ['hello', 5, 'male', 'haah', 'h', 'e', 'l', 'hak', 'python']
2)索引
In [23]: li.remove(li[1])
In [24]: li
Out[24]: ['hello', 'male', 'haah', 'h', 'e', 'l', 'hak', 'python']
3)删除列表
In [29]: del li
5,列表的修改
>>> list1[0] = "fendai"
6,弹出
n [25]: li.pop()
##默认,从最后一位弹出
Out[25]: 'python'
In [26]: li
Out[26]: ['hello', 'male', 'haah', 'h', 'e', 'l', 'hak']
In [27]: li.pop(0) ##弹出第0位元素
Out[27]: 'hello'
####p(o)p:出栈
p(U)sh:入栈
(Q)uit:退出
*************先进后出
stack = []
pro= '''
p(O)p
p(U)sh
(V)iew
(Q)uit
input your choice:
'''
choice = raw_input(pro).lower()
###输入的字母都转换为小写
if choice == 'o':
stack.pop()
##先进后出
print stack
elif choice == 'u':
stack.insert(0,'hello')
print stack
elif choice == 'v':
print stack
elif choice == 'q':
exit(0)
##直接退出
############队列:
**************先进先出
queue = []
pro= '''
p(O)p
p(U)sh
(V)iew
(Q)uit
input your choice:
'''
while True:
choice = raw_input(pro).lower()
if choice == 'o':
queue.pop(0)
###先进先出
print queue
elif choice == 'u':
item =raw_input("item:")
queue.append(item)
print queue
elif choice == 'v':
print queue
elif choice == 'q':
exit(0)
####练习:
打印1-100中所有的偶数
打印1-100中所有的奇数
a = range(1,100,2)
print "1-100中所有的偶数:"
print a
b = range(2,100,2)
print "1-100中所有的奇数:"
print b
列表
最新推荐文章于 2024-05-20 00:30:00 发布