为可变长度列表中的元素指定固定数量的变量

2024-10-05 14:21:23 发布

您现在位置:Python中文网/ 问答频道 /正文

背景:

我有一个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)

Tags: 脚本noneif时间员工pop手指背景
2条回答

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

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

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

基于itertoolsSainath's answer版本:

from itertools import chain, repeat

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

它是否更优雅值得商榷;它确实有一点小小的改进,即timestamps不局限于任何特定类型的iterable。你知道吗

相关问题 更多 >