字典中列表的嵌套循环

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

我有一个包含列表值的词典:

{
'List1' : ['Value1', 'Value2', 'Value3'],
'List2' : ['Value1', 'Value2', 'Value3'],
'List3' : ['Value1', 'Value2', 'Value3'],
}

我想迭代每个列表的值来查找正则表达式,然后创建一个包含这些正则表达式的字典。也就是说,对于我的初始字典的每个列表。我的列表上的每次迭代(前一个例子中的3个)都会创建1行(总共3行),因此我会运行一个代码来创建一个全面的唯一行。

不确定是否清楚,但它看起来应该类似于:

for list in dictionary:
    for value in list:
            column_list_A = []
            if re.search(regex, value):
                column_list_A.append(regex, value).group(1)
            column_list_B = []
            if re.search(regex, value):
                column_list_B.append(regex, value).group(1)
    New_Dictionary = {"column_list_A" : column_list_A, "column_list_B" : column_list_B}
    Df = pd.DataFrame.from_dict(New_Dictionary)
    for column in Df:
        #Code that puts the values of the 3 rows into 1 row

输出应如下所示:

      | Column_list_A  |  Column_list_B
----------------------------------------------------
List1 |  match object  | match object  
----------------------------------------------------
List2 |  match object  | match object  
----------------------------------------------------
List3 |  match object  | match object  

我的问题是:

1)如何实现嵌套的for循环?我尝试过像iteritems()这样的东西,但它没有给出令人满意的结果。对于每个循环,X和Y究竟应该在“for X in Y”中?

2)压痕是否正确?

python regex loops
2个回答
1
投票

如果你希望你的最终输出是一个数据帧,我建议你使用可以自己很好地处理循环和正则表达式的熊猫函数,而不需要for循环。这是一个例子:

import pandas as pd

# read dict in the right orientation
df = pd.DataFrame.from_dict(dictionary, orient="index")

''' # your df will look like this:
>>> df
            0       1       2
List1  Value1  Value2  Value3
List2  Value1  Value2  Value3
List3  Value1  Value2  Value3
'''

# append your regex matches to the dataframe

# e.g. match any of (d,e) followed by a digit
df["match_from_column_0"] = df[0].str.extract(r'([de]\d)')

# e.g. match a digit
df["match_from_column_1"] = df[1].str.extract(r'(\d)')

# save your output as a dataframe
output = df[["match_from_column_0","match_from_column_1"]]

''' # output will look like this:
>>> output
      match_from_column_0 match_from_column_1
List1                  e1                   2
List2                  e1                   2
List3                  e1                   2
'''

# or a dict
output_dict = output.to_dict()
'''
>>> output_dict
{'output1': {'List1': 'e1', 'List2': 'e1', 'List3': 'e1'}, 
'output2': {'List1': 'e2', 'List2': 'e2', 'List3': 'e2'}}
'''

解决您的2个问题:

  • 字典上的循环可能类似于(假设为python3): for dict_key, dict_value in dictionary.items(): # do whatever
  • 列表上的循环可能类似于: for value in my_list: # do whatever
  • 您的第3-8行应该缩进(距离第二行有4个空格用于循环缩进)
  • 按照你的方式(在我看来更难的方式),这是一个建议(if语句应该需要一个else子句+追加空字符串,因为它们会导致你的列表长度不等?):
import re

for key, list_of_values in dictionary.items():
    for value in list_of_values:
        column_list_A = []
        if re.search(regex, value):
            column_list_A.append(re.search(regex, value).group(0))
        else:
            column_list_A.append("")
        column_list_B = []
        if re.search(regex, value):
            column_list_B.append(re.search(regex, value).group(0))
        else:
            column_list_B.append("")
    New_Dictionary = {"column_list_A" : column_list_A, "column_list_B" : column_list_B}
    Df = pd.DataFrame.from_dict(New_Dictionary)
    for column in Df:
        # do your thing

一些文档的引用:

希望有所帮助!


0
投票

如果你可以使用以下dictcomp:

import re
from pprint import pprint

d = {
'List1' : ['Value1', 'Value2', 'Value3'],
'List2' : ['Value1', 'Value2', 'Value3'],
'List3' : ['Value1', 'Value2', 'Value3'],
}

col = ["column_list_A", "column_list_B", "column_list_C"]

def func(a, b, c):
    a = re.match(r'Val(ue\d)', a).group(1)
    b = re.match(r'Valu(e\d)', b).group(1)
    c = re.match(r'Value(\d)', c).group(1)
    return [a, b, c]

new_d = {i: func(*j) for i, *j in zip(col, *d.values())}

pprint(new_d)

输出:

{'column_list_A': ['ue1', 'e1', '1'],
 'column_list_B': ['ue2', 'e2', '2'],
 'column_list_C': ['ue3', 'e3', '3']}
© www.soinside.com 2019 - 2024. All rights reserved.