笨方法学python 习题32-33

习题32 循环和列表

代码如下:

#创建列表
'''
hairs=['brown','blond','red']
eyes=['brown','blue','green']
weights=[1,2,3,4]
'''
#先定义list里面有什么
the_count=[1,2,3,4]
fruits=['apple','orange','pears','apricots']
change=[1,'apple',2,'orange',3,'pears',4,'apricots']
# this first kind of for-loop goes through a list
#for循环
for number in the_count:
    print(f"This is count {number}")
# same as above
#for循环
for fruit in fruits:
    print(f"A fruit of type:{fruit}")
# also we can go through mixed lists too
# notices we have to use {} since we don't know what's in it
#for循环
for i in change:
    print(f"I got {i}")
# we can also build lists, first start with an empty one
elements=[]
# then use the range function to do 0 to 5 counts
#range函数
for i in range(0,6):
    print(f"Adding {i} to the list.")
    # append is a function that lists understand
    elements.append
# now we can't print them out too
for i in elements:
    print(f"Element was: {i}")

结果输出:

This is count 1
This is count 2
This is count 3
This is count 4
A fruit of type:apple
A fruit of type:orange
A fruit of type:pears
A fruit of type:apricots
I got 1
I got apple
I got 2
I got orange
I got 3
I got pears
I got 4
I got apricots
Adding 0 to the list.
Adding 1 to the list.
Adding 2 to the list.
Adding 3 to the list.
Adding 4 to the list.
Adding 5 to the list.

进程已结束,退出代码0

Tips:

- range( ):

  • range( )的功能
    用来返回一个迭代对象,而不仅仅是计算某一个值,所以在实际使用当中range经常搭配for语句使用。
  • range( )的用法
range(终值)            #默认起始值为0
range(起始值,终值[,步长])
  • **起始值:**对象最初迭代开始的值,若缺省起始值的情况下默认为0,例如range(3)等同于range(0,3);

  • **终值:**对象迭代的最终结束值,例如range(0,3)就是按顺序从0,1,2进行迭代;

  • 步长:可以简单的理解为迭代值的跨度,例如range(0,4,2)的意思是按0,2进行迭代

- 注意:range迭代对象遵循左闭右开的原则

  • range( )可以反方向迭代:
    range函数是支持负方向迭代的,把步长设为负数即可,range(0,-8,-2)表示为按0,-2,-4,-6进行迭代。
  • range( )迭代的对象可以通过下标访问
    range( )迭代对象的内容和列表、元组都非常相似,可以通过下标方式访问,range函数也可以理解为一个数列。

例如a=range(1,3),我们用下标来访问a当中的元素,a[0]=1,a[1]=2

a=range(1,3)
print(a)
print(a[0],a[1])

- 22行,直接将elements赋值为range(0,6),无需使用for循环

- append还可以对列表做哪些操作?
append()用于在列表末尾添加新的对象

语法:list.append(obj)
list:列表对象;
obj:添加到列表末尾的对象
append()函数无返回值,但是会修改原本的列表
#!/usr/bin/python
#Filename:append.py
a=[-1,3,'aa',85,90,'dasd']
a.append('add')
print a
——————————————
[-1, 3, 'aa', 85, 90, 'dasd', 'add']
——————————————
#多维数组
import numpy as np
a=[] 
for i in range(5): 
  a.append([])
  for j in range(5): 
    a[i].append(i)
——————————————
[[0, 0, 0, 0, 0],
 [1, 1, 1, 1, 1],
 [2, 2, 2, 2, 2],
 [3, 3, 3, 3, 3],
 [4, 4, 4, 4, 4]]
——————————————
 lst = [1, 2, 3, 4]

lst.append(5)

lst.append('a')

lst.append([1, 2, 3])

lst.append((1, 2, 3))

lst.append({1:'a', 2:'b'})

print(lst)
——————————————
[1, 2, 3, 4, 5, 'a', [1, 2, 3], (1, 2, 3), {1: 'a', 2: 'b'}]
lst.extend(iterable):这里将一个可迭代对象插入列表中,作为列表的一个扩展
将原来的iterable数据结构打破,将可迭代对象iterable中的元素逐个添加到列表lst中,作为lst的元素

lst.insert(index, new_item):这里index是列表lst的插入位置,new_item是插入列表的对象,
类型同append方法中的参数类型

习题33 while循环

代码如下:

# while 循环
i = 0
numbers=[]

while i < 6:
    print(f"At the top i is {i}")
    numbers.append(i)

    i=i+1
    print("Number now:",numbers)
    print(f"At the bottom i is {i}")
    print("The numbers:")

    for num in numbers:
        print(num)

结果输出:

At the top i is 0
Number now: [0]
At the bottom i is 1
The numbers:
0
At the top i is 1
Number now: [0, 1]
At the bottom i is 2
The numbers:
0
1
At the top i is 2
Number now: [0, 1, 2]
At the bottom i is 3
The numbers:
0
1
2
At the top i is 3
Number now: [0, 1, 2, 3]
At the bottom i is 4
The numbers:
0
1
2
3
At the top i is 4
Number now: [0, 1, 2, 3, 4]
At the bottom i is 5
The numbers:
0
1
2
3
4
At the top i is 5
Number now: [0, 1, 2, 3, 4, 5]
At the bottom i is 6
The numbers:
0
1
2
3
4
5

进程已结束,退出代码0

Tips:

将while循环改成一个函数,将测试条件(i<6)中的6换成一个变量

# while 循环
i = 0
a=i-2
numbers=[]

while True:
        print(f"At the top i is {a}")
        numbers.append(i)
        i=i+1
if a == 5:
    print("Number now:",numbers)
else:
    print(f"At the bottom i is {i}")
    print("The numbers:")

    for num in numbers:
        print(num)
        break
——————————————————————————————————————
At the top i is -2
At the top i is -2
At the top i is -2
At the top i is -2
At the top i is -2
At the top i is -2
At the top i is -2
At the top i is -2
At the top i is -2
....

for循环和range把脚本写一遍

# while 循环
i = 0
a=i-2
numbers=[]
for a in range(1,12,2):
    print(a)
'''
#让a等于range函数中取到的所有值,for循环可以遍历循环内所有的元素。
#此时range()表示:从1开始取值到11,每个两个数字取一个数。
'''
while True:
        print(f"At the top i is {a}")
        numbers.append(i)
        i=i+1
if a == 5:
    print("Number now:",numbers)
else:
    print(f"At the bottom i is {i}")
    print("The numbers:")

    for num in numbers:
        print(num)
        break
——————————————————————————---
At the top i is 11
At the top i is 11
At the top i is 11
At the top i is 11
At the top i is 11
At the top i is 11
At the top i is 11
At the top i is 11
.....

for循环和while循环的区别
for循环只能对一些东西的集合进行循环,适合简单任务;
while循环可以对任何对象进行循环,更复杂;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值