Python 有没有更简洁的方法将localtime转换为单个二进制列表?
我尝试使用localtime,并将其转换为单独的反向二进制数组/列表 这是我的工作代码:Python 有没有更简洁的方法将localtime转换为单个二进制列表?,python,python-2.7,Python,Python 2.7,我尝试使用localtime,并将其转换为单独的反向二进制数组/列表 这是我的工作代码: secs = time.localtime() year, month, day, hour, minute, second, weekday, yearday, daylight = secs seconds_string = "{0:#b}".format(second) seconds_string = seconds_string[2:] seconds_l
secs = time.localtime()
year, month, day, hour, minute, second, weekday, yearday, daylight = secs
seconds_string = "{0:#b}".format(second)
seconds_string = seconds_string[2:]
seconds_list = list(seconds_string[::-1])
minutes_string = "{0:#b}".format(minute)
minutes_string = minutes_string[2:]
minutes_list = list(minutes_string[::-1])
hours_string = "{0:#b}".format(hour)
hours_string = hours_string[2:]
hours_list = list(hours_string[::-1])
如果可能的话,我想让它更简洁,但是像下面这样的尝试是行不通的
seconds_list = list("{0:#b}".format(second)[2::-1])
有没有一种方法可以做到这一点,而我却不知道?你真正想要的是什么
seconds_list = list("{0:#b}".format(second)[:1:-1])
语法有点奇怪;切片是从:到:步骤进行的
。这是一个从
到的的,一个到的的的,以及一个步骤-1
;当步长为负时,from
默认为字符串的结尾,因此这意味着“从字符串的结尾向后,直到但不包括位置1”。您想要的实际上是
seconds_list = list("{0:#b}".format(second)[:1:-1])
语法有点奇怪;切片是从:到:步骤进行的。这是一个从
到的的,一个到的的的,以及一个步骤-1
;当步长为负时,from
默认为字符串的结尾,因此这意味着“从字符串的结尾向后,直到但不包括位置1”。是的,有:
>>> ''.join('{0:#b}'.format(x)[2:] for x in time.localtime())
'11111011100100011110001111001110011110111001'
相反,您可以在末尾添加[::-1]
但这并不意味着你应该这么做。将清晰性置于较短代码之上。是的,有:
>>> ''.join('{0:#b}'.format(x)[2:] for x in time.localtime())
'11111011100100011110001111001110011110111001'
相反,您可以在末尾添加[::-1]
但这并不意味着你应该这么做。在较短的代码上面放清楚一点。在这里使用生成器表达式而不是
map
会使它更加清晰:IMO:'.join({0:#b}.format(x)[2:]表示时间上的x.localtime())[::-1]
@Dougal:aboutmap
与列表理解(或生成器)相比,这绝对是个人偏好的问题。如果函数已经创建(只是为了避免lambda
),我通常更喜欢map
,并在我执行新操作时列出理解。你是对的,这个生成器在这里看起来更好。使用生成器表达式而不是map
,这会让IMO:'.join({0:#b}.format(x)[2:]for x in time.localtime())[:::-1]
@Dougal:关于map
与列表理解(或生成器),这绝对是个人偏好的问题。如果函数已经创建(只是为了避免lambda
),我通常更喜欢map
,并在我执行新操作时列出理解。你说得对,那台发电机在这里看起来更好。谢谢!它看起来也适用于seconds\u list=list(bin(second)[:1:-1])
谢谢!它看起来也适用于seconds\u list=list(bin(second)[:1:-1])