(七)语句<1>基础

1.两个变量的值对调

>>> a=1
>>> b=2
>>> a,b=b,a
>>> a
2
>>> b
1

2.同时赋值

>>> m=n='King'
>>> m
'King'
>>> n
'King'
>>> id(m)
51439128
>>> id(n)
51439128

3.了解这种三元操作符写法:

>>> name='Jim Green' if 'right' else 'wrong'
>>> name
'Jim Green'
>>> name='Don' if '' else 'empty'
>>> name
'empty'
>>> name='Jim Green' if bool('right') else 'wrong'
>>> name
'Jim Green'
>>> name='Jim Green' if True else 'wrong'
>>> name
'Jim Green'
>>> name='Jim Green' if False else 'wrong'
>>> name
'wrong'

4.两种遍历字符串的方式:

>>> word='python'
>>> for i in word:
    print(i)

    
p
y
t
h
o
n
>>> for i in range(len(word)):
    print(word[i])

    
p
y
t
h
o
n
  • 遍历字典:
dict1=dict([('name','Jim Green'),('age','20')])
for k in dict1:
    print(k)
for k in dict1.keys():
    print(k)
for k,v in dict1.items():
    print(k+' --> '+v)
>>>
age
name
age
name
age --> 20
name --> Jim Green
  • 遍历元组
list1=[1,2,3,4,5]
tuple1=tuple(list1)
for i in tuple1:
    print(i)
for i in range(len(tuple1)):
    print(tuple1[i])
>>>
1
2
3
4
5
1
2
3
4
5

5.判断对象是否可迭代,前面已有实例,这边是另一种方法:

# 利用collections库
>>> import collections
>>> isinstance(321,collections.Iterable)
False
>>> isinstance([321],collections.Iterable)
True
# 之前的方法是利用内建函数
>>> hasattr(321,'__iter__')
False
>>> hasattr([321],'__iter__')
True

6.zip()函数---优雅的"组合序列"

  • 常规方法
# 对应的元素相加
a=[1,2,3,4,5]
b=[9,8,7,6,5]
c=[]
for i in range(len(a)):
    c.append(a[i]+b[i])
print(c)
>>>[10, 10, 10, 10, 10]
  • 优雅的方法
>>> a=[1,2,3,4,5]
>>> b=[9,8,7,6,5]
>>> zip(a,b)

>>> list(zip(a,b))
[(1, 9), (2, 8), (3, 7), (4, 6), (5, 5)]
>>> c=[]
>>> for m,n in list(zip(a,b)):
    c.append(m+n)

    
>>> c
[10, 10, 10, 10, 10]
  • 基础实例
>>> a="qiwsir"
>>> b='github'
>>> zip(a,b)

#对应的字符组合成元组,放在列表
>>> list(zip(a,b))
[('q', 'g'), ('i', 'i'), ('w', 't'), ('s', 'h'), ('i', 'u'), ('r', 'b')]
>>> c=[1,2,3]
>>> d=[9,8,7,6]
>>> zip(c,d)

>>> list(zip(c,d))
# 取最短的长度,末尾的6被抛弃
[(1, 9), (2, 8), (3, 7)]
>>> m={'name','lang'}
>>> n={'qiwsir','python'}
# 组合集合
>>> list(zip(m,n))
[('name', 'python'), ('lang', 'qiwsir')]
>>> type(m)

# 组合字典,视键为序列
>>> s={'name':'qiwsir'}
>>> t={'lang':'python'}
>>> list(zip(s,t))
[('name', 'lang')]
>>> 
  • 传入单个对象,有点特殊
>>> a=[1,2,3,4,5]
>>> b='qiwsir'
>>> list(zip(a))
[(1,), (2,), (3,), (4,), (5,)]
>>> list(zip(b))
[('q',), ('i',), ('w',), ('s',), ('i',), ('r',)]
  • 练习的例子:
a=[1,2,3,4,5]
b=['name','age','website']
"""c=list(zip(a,b))
d=[]
for m,n in c:
    d.append(str(m)+'.'+n)
print(d)"""
c=[]
for i in range(len(b)):
    #c.append(str(a[i])+'.'+b[i])
    c.extend(str(a[i])+'.'+b[i])
print(c)
>>>
# extend()会一个一个拆分
['1', '.', 'n', 'a', 'm', 'e', '2', '.', 'a', 'g', 'e', '3', '.', 'w', 'e', 'b', 's', 'i', 't', 'e']
  • zip()的进一步组合:
>>> a=[2,4,6,8]
>>> b=[11,13,15,17]
>>> result=list(zip(a,b))
# 第一次组合
>>> result
[(2, 11), (4, 13), (6, 15), (8, 17)]
# 添加*号,再次组合
>>> result2=list(zip(*result))
>>> result2
[(2, 4, 6, 8), (11, 13, 15, 17)]
# 再次*,回到原来
>>> result3=list(zip(*result2))
>>> result3
[(2, 11), (4, 13), (6, 15), (8, 17)]
# **表示映射,不符合映射,报错
>>> result4=list(zip(**result3))
Traceback (most recent call last):
  File "", line 1, in 
    result4=list(zip(**result3))
TypeError: type object argument after ** must be a mapping, not list
  • 字典的键值对调
# 常规方法
dict1={'name':'Jim','age':'20','website':'sina.com'}
dict2={}
for k,v in dict1.items():
    dict2[v]=k
print(dict2)
>>>{'sina.com': 'website', 'Jim': 'name', '20': 'age'}
# zip()方法
>>> list(zip(dict1.values(),dict1.keys()))
[('Jim', 'name'), ('sina.com', 'website'), ('20', 'age')]
>>> dict(list(zip(dict1.values(),dict1.keys())))
{'sina.com': 'website', 'Jim': 'name', '20': 'age'}

7.内建enumerate()---返回传入对象的索引和值:

# 常规做法
dates=['Monday','Tuesday','Wednesday']
for i in range(len(dates)):
    print(dates[i]+" is "+str(i))
>>>
Monday is 0
Tuesday is 1
Wednesday is 2
# 使用enumerate()
dates=['Monday','Tuesday','Wednesday']
# >>> list(enumerate(dates))
#[(0, 'Monday'), (1, 'Tuesday'), (2, 'Wednesday')]
#>>> list(zip(*list(enumerate(dates))))
#[(0, 1, 2), ('Monday', 'Tuesday', 'Wednesday')]
for (i,day) in enumerate(dates):
    print(day+" is "+str(i))
>>>
Monday is 0
Tuesday is 1
Wednesday is 2
  • 设置索引的值
>>> list1=['spring','summer','autumn','winter']
>>> text1=list(enumerate(list1))
>>> text1
[(0, 'spring'), (1, 'summer'), (2, 'autumn'), (3, 'winter')]
>>> text2=list(enumerate(list1,start=1))
>>> text2
[(1, 'spring'), (2, 'summer'), (3, 'autumn'), (4, 'winter')]
  • 替换字符串的方法:
# 把字符串"TeacherCang"改为"PHP"
message="Do you love TeacherCang ? TeacherCang is a good teacher."
text1=message.split(' ')
"""for i in range(len(text1)):
    if 'TeacherCang' in text1 and text1[i]=='TeacherCang':
        text1[i]='PHP'
print(text1)"""
for i,target in enumerate(text1):
    if 'TeacherCang' in target:
        text1[i]='PHP'
print(text1)

8.列表解析:

>>> squares=[x*x for x in range(1,11)]
>>> squares
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> target='King' if True else 'Green'
>>> target
'King'

你可能感兴趣的:((七)语句<1>基础)