将固定数量的变量分配给可变长度列表中的元素

时间:2014-10-09 12:48:19

标签: python variable-assignment iterable-unpacking

背景:

我有一个python脚本来检查员工的工作时间。每位员工都有上午和下午的班次,午餐时间介于两者之间,每次他们放手指都会记录新的时间戳。

因此,根据每天的时间,当天列表中可能有0到4个时间戳。

问题:"我怎样才能解开'时间戳到相应的变量,避免所有这些丑陋,重复的代码?"

morning_entry = None
morning_leave = None
afternoon_entry = None
afternoon_leave = None

timestamps = get_timestamps()

if timestamps:
    morning_entry = timestamps.pop(0)

if timestamps:
    morning_leave = timestamps.pop(0)

if timestamps:
    afternoon_entry = timestamps.pop(0)

if timestamps:
    afternoon_leave = timestamps.pop(0)

2 个答案:

答案 0 :(得分:1)

一个简单的解决方案,但可能不是那么优雅

morning_entry,morning_leave,afternoon_entry,afternoon_leave=(timestamps+[None]*4)[:4]

只需在列表前用Nones填充它,然后切片

答案 1 :(得分:0)

基于itertools的{​​{3}}版本:

from itertools import chain, repeat

(morning_entry,
 morning_leave,
 afternoon_entry,
 afternoon_leave) = chain(timestamps, repeat(None, 4))

它是否更优雅是值得商榷的;它确实有一个小的改进,timestamps不限于任何特定类型的可迭代。

相关问题