使用 python 代码块将 Google Sheets 中的原始行更改为列表列表

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

我正在使用从 Google 表格中提取到 Zapier 的数据集。数据集如下所示,我正在编写一个代码块来将用户值与数据集中的所有值进行比较。

Bank   |   Product |   Bundle |   Restriction Geo |   Restriction Geo 2 |   Restriction Geo Val |   Restriction Type |   Restriction Type Val
_______________________________________________________________________________________________________________________________________________
Wells      Savings     Ind,Sp      State                                      NY,CA,NV                General                100%                                                  
JMorg       IRA        Ind         County                  CA                 Solano, Marin           Claims                 3
Goldman    Savings     All         Zip                                        94954,27717,38002       Credit Score           680
Wells      Savings     All         Zip                                        48441                   General                100%

我遇到的问题是,某些单元格本身就是 CSV,因此我无法单独提取每个格式化列并通过 .split(",") 拆分它们。我认为我需要的是处理原始行,其格式如下:

[["Wells","Savings","Ind,Sp","State","","NY,CA,NV","General","100%"],["JMorg","IRA","Ind","County","CA","Solano,Marin",...,"48441","General","100%"]]

原始行作为单个文本字符串出现,而不是列表的列表,这正是我想要的。我尝试运行这个正则表达式模式

(?<=\[).+?(?=\])

将每个匹配项提取为行项目,但这会保留左括号和右括号,并将值保留在引号内而不是列表。我想要得到的本质上是一个列表列表的列表,类似于;

[[Wells,Savings,[Ind,Sp],State, ,[NY,CA,NV]...]]

这样我可以做类似的事情(我已经写了这部分,它适用于测试数据,但测试数据已经格式化为列表的列表)。

for d in data_set:
   temp_val = []
   if d[0] == "Wells":
      temp_val = d[2].split(",")
      for t in temp_val:
         if t == "Ind":
            ###do something"
      temp_val.clear()
python python-3.x google-sheets zapier
1个回答
0
投票

我相信您要做的就是循环遍历列表并将任何逗号分隔值转换为主列表内的嵌套列表。下面的代码块将实现这一点。

输入及代码:

lists= [['Wells', 'Savings', 'Ind,Sp', 'State', '', 'NY,CA,NV', 'General', '100%'], ['JMorg', 'IRA', 'Ind', 'County', 'CA', 'Solano,Marin', '48441', 'General', '100%']]
for l in lists:
    for idx,word in enumerate(l):
            if "," in word:
                    l[idx] = word.split(",")

输出:

[['Wells', 'Savings', ['Ind', 'Sp'], 'State', '', ['NY', 'CA', 'NV'], 'General', '100%'], ['JMorg', 'IRA', 'Ind', 'County', 'CA', ['Solano', 'Marin'], '48441', 'General', '100%']]
© www.soinside.com 2019 - 2024. All rights reserved.