列表推导,笛卡尔乘积 colors = ['block','white'] sizes = ['s','n','l'] tshirts = [(color,size) for color in colors for size in sizes] print(tshirts) [('block', 's'), ('block', 'n'), ('block', 'l'), ('white', 's'), ('white', 'n'), (
列表推导,笛卡尔乘积
colors = ['block','white']sizes = ['s','n','l']
tshirts = [(color,size) for color in colors for size in sizes]
print(tshirts)
元祖不仅仅是不可变的列表
元组和记录
lax_coordinates = (32.9425,-118.405689)city,year,pop,chg,area = ('tokyo',2003,32450,0.66,8014)
traveler_ids = [('usa','31195855'),('bra','ce342567'),('esp','xda205856')]
for passport in sorted(traveler_ids):
print('%s/%s' % passport)
for country,_ in traveler_ids:
print(country)C:\Python\python3.6.5\python.exe E:/pythoncode/day07/01.py
bra/ce342567
esp/xda205856
usa/31195855
usa
bra
esp
元组拆包
lat,lng = lax_coordinates
print(lat)
print(lng)
还可以用*把一个可迭代对象拆开作为函数的参数
print(divmod(20,8))#(2, 4)
t=(20,8)
q,r=divmod(*t)
print(q,r)
#2 4
print(a,b,reset)
具名元组
from collections import namedtupleCity = namedtuple('City',('name','country','popolation','coordinates'))
tokyo = City('Tokyo','jp','36.933',(35.6,139.66))
print(tokyo)
#City(name='Tokyo', country='jp', popolation='36.933', coordinates=(35.6, 139.66))
print(tokyo.popolation)
#36.933
print(City._fields)
#('name', 'country', 'popolation', 'coordinates')
latlong = namedtuple('latlong','lat long')
delhi_data = ('delhi ncr' , 'in',21.935,latlong(28.36,77.69))
delhi = City._make(delhi_data)
print(delhi)
#City(name='delhi ncr', country='in', popolation=21.935, coordinates=latlong(lat=28.36, long=77.69))
print(delhi._asdict())
#OrderedDict([('name', 'delhi ncr'), ('country', 'in'), ('popolation', 21.935), ('coordinates', latlong(lat=28.36, long=77.69))])