在列表中的偶数和奇数元素上传递两个不同的函数

时间:2019-01-14 19:07:01

标签: python list

我想在列表上传递两个不同的函数。一种用于奇数元素,另一种用于偶数元素。

列表如下:`

lst = [2856064, 5819, 2856936, 8557, 2858224, 7744, 2859392, 8333, 2859718, 7588, 2860220, 10556, 2861336, 9298, 2863080, 6912, 2865340, 7929, 2866040, 9513, 2866350, 7828, 2867228, 10795, 2868044, 12431, 2869740, 8922, 2870080, 10792, 2870392, 7382, 2871584, 6873, 2872800, 7271, 2873864, 6776, 2875664, -1, 2876294, 8495]

对于偶数元素,我想将其转换为UTC格式的时间戳。 我当前的代码: [datetime.utcfromtimestamp((time+21564000)*60).strftime('%Y%m%d') for time in lst[::2]]另一方面,偶数元素将保持不变,除非为-1,否则返回0。我当前的代码:

[0 if tag==-1 else tag for tag in lst[1::2]]

此外,我也只想获取“ 20160618”之后的信息。也就是说,我的预期结果看起来像这样[20160618, 7271, 20160618, 6776, 20160619, 0, 20160620, 8495]

p.s。有可能一次完成列表理解吗?

2 个答案:

答案 0 :(得分:1)

以下是通常通过理解来解决此问题的方法:

# a is some list
# f1 is a function that's supposed to map the odd elements
# f2 is a function that's supposed to map the even elements
[f1(x) if i%2 else f2(x) for i, x in enumerate(a)]

答案 1 :(得分:1)

您可以使用带有三元表达式的enumerate()% 2来做任何事情-使用max(x,0)可以将-1替换为0,因为-1是唯一的负值:

from datetime import datetime

lst = [2856064, 5819, 2856936, 8557, 2858224, 7744, 2859392, 8333, 2859718, 
      7588, 2860220, 10556, 2861336, 9298, 2863080, 6912, 2865340, 7929, 2866040, 
      9513, 2866350, 7828, 2867228, 10795, 2868044, 12431, 2869740, 8922, 2870080,
      10792, 2870392, 7382, 2871584, 6873, 2872800, 7271, 2873864, 6776, 2875664, 
      -1, 2876294, 8495]

k = [datetime.utcfromtimestamp((x+21564000)*60).strftime('%Y%m%d') 
     if i%2 == 0 else max(0,x) for i,x in enumerate(lst)]

print(k)

输出:

['20160606', 5819, '20160606', 8557, '20160607', 7744, '20160608', 8333, 
 '20160608', 7588, '20160609', 10556, '20160610', 9298, '20160611', 6912, 
 '20160612', 7929, '20160613', 9513, '20160613', 7828, '20160614', 10795, 
 '20160614', 12431, '20160615', 8922, '20160616', 10792, '20160616', 7382, 
 '20160617', 6873, '20160618', 7271, '20160618', 6776, '20160619', 0, 
 '20160620', 8495]

要获取20160618之后的零件,请获取其索引并切片:

b = k[ k.index('20160618'):]
print(b) # ['20160618', 7271, '20160618', 6776, '20160619', 0, '20160620', 8495]

您的日期字符串格式正确,便于进行词法比对'20170101',然后是'20161231'-因此,您可以使用字典法比较在“不在列表中的日期”之后找到“日期”:

t= ['20160606', 5819, '20160606', 8557, '20160607', 7744, '20160608', 8333, 
 '20160608', 7588, '20160609', 10556, '20160610', 9298, '20160611', 6912, 
 '20160612', 7929, '20160613', 9513, '20160613', 7828, '20160614', 10795, 
 '20160614', 12431, '20160615', 8922, '20160616', 10792, '20160616', 7382, 
 '20160617', 6873, '20160618', 7271, '20160618', 6776, '20160619', 0, 
 '20160620', 8495, '20170618', 7271, '20180618', 7271,]

index = 0
for idx, k in enumerate(t):
    if idx % 2 == 0 and k > "20160620":
        index = idx
        break

print(t[index:]) # ['20170618', 7271, '20180618', 7271]