python3基础: 元组tuple、 列表list、 字典dict、集合set。 迭代器、生成器

一、元组:  tuple

Python 的元组与列表类似,不同之处在于元组的元素不能修改。

元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组

复制代码
tup2 = (111, 22, 33, 444, 55, 6, 77 )
for x in (tup2):      #遍历
    print(x)


list2 = [111, 22, 33, 444, 55, 6, 77 ]
tup2 = tuple(list2)    #将列表转变为元组
复制代码

二、列表:  list

遍历列表:

复制代码
#遍历列表
list1 = [1, 2, 3, 6, 5, 4]
for x in list1:
    print(x, end=",")  # 运行结果:1,2,3,6,5,4,

for i in range(len(list1)):
    print("序号:", i, "  值:", list1[i])

for i, val in enumerate(list1):
    print("序号:", i, "  值:", val)

for i in list1:
    idx = list1.index(i) # 索引
    if (idx < len(list1) - 1):
        print(i, '---------', list1[idx + 1])
复制代码

  

排序列表、判断元素是否在列表中:

复制代码
list1 = [1,2,3,6,5,4]
#排序列表(正序)
list1.sort()
for x in list1:
    print(x, end=",")   #运行结果:1,2,3,4,5,6,
print("")

#排序列表(倒序)
list1.reverse()
for x in list1:
    print(x, end=",")   #运行结果:6,5,4,3,2,1,
print("")

#判断元素是否存在于列表中
if 5 in list1:
    print("5 在list1中")

#在末尾追加新的元素
list1.append(555)
list1.append(555)
print(list1)

#统计某个元素在列表中出现的次数
print("出现",list1.count(555),"次")

#移除元素,并返回值(默认是移除最后一个)
print(list1.pop(0)) # 移除第一个
print(list1.pop()) # 移除最后一个
复制代码

随机列表

复制代码
import random

#返回一个随机的项目
print(random.choice(range(100)))
print(random.choice([1, 2, 3, 5, 9]))
print(random.choice('Hello World'))

ls1 = [20, 16, 10, 5];
random.shuffle(ls1) #返回重新洗牌列表,随机
复制代码

三、字典:  dict

复制代码
dict = {'name': 'pp', 'age': 20, "gender": "man"}
dict["name"] = "sss"

for key in dict.keys():  # 遍历字典。字典的 keys() 方法以列表返回可遍历的(键) 元组数组。
    print(key)

for val in dict.values():  # 遍历字典。字典的 values() 方法以列表返回可遍历的(值) 元组数组。
    print(val)

for key, val in dict.items():  # 遍历字典。字典的 items() 方法以列表返回可遍历的(键, 值) 元组数组。
    print(key, " : ", val)
复制代码

  

字典的多级嵌套:

复制代码
citys={
    '北京':{
        '朝阳':['国贸','CBD','天阶'],
        '海淀':['圆明园','苏州街','中关村','北京大学'],
        '昌平':['沙河','南口','小汤山',],
        '怀柔':['桃花','梅花','大山']
    },
    '河北':{
        '石家庄':['石家庄A','石家庄B','石家庄C'],
        '张家口':['张家口A','张家口B','张家口C']
    }
}
for i in citys['北京']:
    print(i)

for i in citys['北京']['海淀']:
    print(i)
复制代码

四、集合:        set

集合(set)是一个无序不重复元素的序列。 基本功能是进行成员关系测试和删除重复元素。

集合无序,元素不能重复。

去重:将列表转化为集合,集合再转化为列表,就可以去重。

可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。

复制代码
student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'}
print(student)   # 输出集合,重复的元素被自动去掉 {'Mary', 'Jim', 'Rose', 'Jack', 'Tom'} 

# 成员测试
if('Rose' in student) :
    print('Rose 在集合中')
else :
    print('Rose 不在集合中')
#Rose 在集合中
复制代码

补充:相互转换

1、元组 => 列表 

tuple1 = (123, 'haha', 'she', 'hehe')
list1 = list(tuple1)   #将元组转换为列表。运行结果:[123, 'haha', 'she', 'hehe']
print(list1)

2、字符串 <=> 列表

复制代码
str1 = '天地玄黄宇宙洪荒'
list1 = list(str1)  # 字符串转为列表
str2 = "".join(list1)  # 列表转为字符串
print(str2)

str1 = '天地,玄黄,宇宙,洪荒'
list1 = str1.split(",")  # 字符串转为列表
print(list1)

str1 = '天地玄黄宇宙洪荒'
str2 = str1[::-1]  # 字符串倒序
print(str2)
复制代码

迭代器、生成器:    http://www.runoob.com/python3/python3-iterator-generator.html

迭代器有两个基本的方法:iter() 和 next()

复制代码
import sys  # 引入 sys 模块

list = [1, 2, 3, 4]
it = iter(list)  # 创建迭代器对象

while True:
    try:
        print(next(it))
    except StopIteration:
        sys.exit()
复制代码

使用了 yield 的函数被称为生成器(generator)。  跟普通函数不同的是,生成器是一个返回迭代器的函数,只能用于迭代操作

复制代码
import sys
def fibonacci(n):  # 生成器函数 - 斐波那契
    a, b, counter = 0, 1, 0
    while True:
        if (counter > n):
            return
        yield a
        a, b = b, a + b
        counter += 1

f = fibonacci(10)  # f 是一个迭代器,由生成器返回生成

while True:
    try:
        print(next(f), end=" ")
    except StopIteration:
        sys.exit()
复制代码

Map,Filter,Reduce

  • Map会将一个函数映射到一个输入列表的所有元素上。
  • filter过滤列表中的元素,并且返回一个由所有符合要求的元素所构成的列表
  • 当需要对一个列表进行一些计算并返回结果时,Reduce 是个非常有用的函数。

http://docs.pythontab.com/interpy/Map_Filter/Map/

复制代码
ls1 = [1, 2, 3, 4, 5]
ls2 = list(map(lambda x: x ** 2, ls1))    #加了list转换,是为了python2/3的兼容性。  在python2中map直接返回列表,但在python3中返回迭代器
print(ls2)      # [1, 4, 9, 16, 25]

ls1 = range(-5, 5)
ls2 = filter(lambda x: x > 0, ls1)
print(list(ls2))  # [1, 2, 3, 4]

from functools import reduce
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])  # 计算一个整数列表的乘积
print(product) # 24
复制代码

装饰器:

复制代码
def a(arg):
    pass
def b(arg):
    pass
def c(arg):
    pass

def decorator(func):
    def wrapper(*arg, **kw)
        print ('Start ---' , func)
        return func(*arg, **kw)
    return wrapper

a = decorator(a)
b = decorator(b)
c = decorator(c)
复制代码

https://www.zhihu.com/question/26930016

...

猜你喜欢

转载自www.cnblogs.com/valorchang/p/11282415.html