对多个变量的理解列表,以便将结果连接到字符串列表中



我有两个列表。我想连接以获得字符串列表。第一个列表由字符串组成第二个列表由时间戳组成。

我会将以下内容与理解列表连接在一行中。

#just for creating something similar to my actual situation
import pandas as pd
quarter=["First Quarter","Second Quarter","Third Quarter","Fourth Quarter"]
quarter_forecast_day=pd.date_range(start="12/15/2020",periods=4)

我想要这样的东西:

str(quarter[x]+'n'+quarter_forecast[y].strftime("%d/%m/%Y"))

我尝试过的:

#quarter_label=[str(quarter[x]+'n'+y.strftime("%d/%m/%Y")) for x,y in [quarter, quarter_forecast_day]]
#too many values to unpack (expected 2)
#quarter_label=[str(quarter[x]+'n'+y.strftime("%d/%m/%Y")) for x,y in (quarter, quarter_forecast_day)]
#too many values to unpack (expected 2)
#quarter_label=[str(quarter[x]+'n'+y.strftime("%d/%m/%Y")) for x,y in quarter, quarter_forecast_day]
#invalid sintax
#quarter_label=[lambda x,y:str(quarter[x]+'n'+y.strftime("%d/%m/%Y") for x,y in [quarter, quarter_forecast]]
#invalid sintax
quarter_label=[lambda x,y:str(quarter[x]+'n'+y.strftime("%d/%m/%Y") for x,y in (quarter, quarter_forecast)]
#invalid sintax

在提问之前,我读了这个问题,这个和这个。但我仍在努力寻找合适的方法来应用它

尝试使用zip:

quarter_label = [q+'n'+qf.strftime("%d/%m/%Y") for q, qf in zip(quarter, quarter_forecast_day)]
>>> print(quarter_label)
['First Quartern15/12/2020', 'Second Quartern16/12/2020', 'Third Quartern17/12/2020', 'Fourth Quartern18/12/2020']

首先,不需要str(),因为您要连接3个字符串(strftime返回一个字符串(。

其次,对于双变量理解列表,您需要使用两个for循环,如下所示:

quarter_label = [quarter[x] + 'n' + quarter_forecast[y] for x in range(len(quarter)) for y in range(len(quarter_forecast))]

代码的问题在于,您正在对列表中的项进行迭代,但在表达式中使用它们作为索引。使用项目迭代:

quarter_label = [q + 'n' + f for q in quarter for f in quarter_forecast]

结果:

['First Quartern15/12/2020', 'First Quartern16/12/2020', 'First Quartern17/12/2020', 'First Quartern18/12/2020', 'Second Quartern15/12/2020', 'Second Quartern16/12/2020', 'Second Quartern17/12/2020', 'Second Quartern18/12/2020', 'Third Quartern15/12/2020', 'Third Quartern16/12/2020', 'Third Quartern17/12/2020', 'Third Quartern18/12/2020', 'Fourth Quartern15/12/2020', 'Fourth Quartern16/12/2020', 'Fourth Quartern17/12/2020', 'Fourth Quartern18/12/2020']

相关内容

  • 没有找到相关文章

最新更新