• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
孙龙 程序员
少时总觉为人易,华年方知立业难
博客园    首页    新随笔    联系   管理    订阅  订阅
序列构成的数组

列表推导,笛卡尔乘积

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'), ('white', 'l')]

  

元祖不仅仅是不可变的列表

元组和记录

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

  

 元组拆包

 

lax_coordinates = (32.5985,-118.4582556)
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

 

a,b,*reset = range(5)
print(a,b,reset)

具名元组

from collections import namedtuple

City = 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))])

 

 

 

 

本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/articles/9543167.html

posted on 2018-08-27 16:50  孙龙-程序员  阅读(106)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3