笨方法学习Python-习题32: 循环和列表

如何创建列表:

list1 = [ ' Google ' , ' Runoob ' , 1997 , 2000 ] ;
list2 = [ 1 , 2 , 3 , 4 , 5 ] ;
list3 = [ " a " , " b " , " c " , " d " ] ;
# coding=utf-8

the_count = [1,2,3,4,5]
fruits = ['apples','oranges','pears','apricots']
change = [1,'pennies',2,'dimes',3,'quarters']

# this first kind of for-loop goes through a list 
for number in the_count:
    print("This is count %d" % number)

# same as above
for fruit in fruits:
    print("A fruit of type: %s" % fruit)

# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it 
for i in change:
    print("I got %r" % i)

# we can also build lists,first start with an empty one
#elements = []
elements = range(0,6)

'''
# then use the range function to do 0 to 5 counts
for i in range(0,6):
    print("Adding %d to the list." % i)
    # append is a function that lists understand
    elements.append(i)
'''
# now we can print them out too 
for i in elements:
    print("Element was: %d" % i)

"""
可以直接将 elements 赋值为 range(0,6),而无需使用 for 循环? 
大家可以实际操作下,脚本里已经做修改
"""


Python列表函数&方法

Python3中列表函数:
1len(list)
列表元素个数
2max(list)
返回列表元素最大值
3min(list)
返回列表元素最小值
4list(seq)
将元组转换为列表


Python3中的一些方法:
1list.append(obj)
在列表末尾添加新的对象
2list.count(obj)
统计某个元素在列表中出现的次数
3list.extend(seq)
在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
4list.index(obj)
从列表中找出某个值第一个匹配项的索引位置
5list.insert(index, obj)
将对象插入列表
6list.pop(obj=list[-1])
移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
7list.remove(obj)
移除列表中某个值的第一个匹配项
8list.reverse()
反向列表中元素
9list.sort([func])
对原列表进行排序
10list.clear()
清空列表
11list.copy()
复制列表

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值