如何在日期时间df上使用if语句将for循环转换为列表理解

问题描述 投票:1回答:2

我正在尝试将以下带if语句的for循环转换为列表理解。

# Create dictionary to hold results
    trip_counts = {'AM': 0, 'PM': 0}

# Loop over all trips
for trip in onebike_datetimes:
  # Check to see if the trip starts before noon
  if trip['start'].hour < 12:
    # Increment the counter for before noon
    trip_counts["AM"] += 1
  else:
    # Increment the counter for after noon
    trip_counts["PM"] += 1

我尝试过

[trip_counts["AM"]+=1 if trip['start'].hour <12 else trip_counts['PM']+= 1 for trip in onebike_datetimes] 

但是我不断收到语法错误

python list-comprehension
2个回答
0
投票

分配是陈述。语句在列表理解中不可用。使用循环


0
投票

保持循环很清晰。

如果您真的想利用列表理解,可以执行以下操作:

l = ["AM" if trip["start"].hour < 12 else "PM" for trip in onebike_datetimes]
trip_counts = {i: l.count(i) for i in l}

((如果使用此,则无需初始化trip_counts

© www.soinside.com 2019 - 2024. All rights reserved.