Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何遍历数组?_Python - Fatal编程技术网

Python 如何遍历数组?

Python 如何遍历数组?,python,Python,我刚刚开始学习python,我试图通过一个简单的for-循环从数组中传递一些术语,该循环使用基于正则表达式的模式进行搜索 ethnicities\u stems=[“宗教”、“天主教”、“抗议”]] 对于人种中的词干\u词干: 民族性\u模式=重新编译(r'.*.+词干+'.*'.') 种族=扩展.loc[lambda x:x['queryterm'].str.contains(种族模式,regex=True)] writer=pd.ExcelWriter(词干+'.xlsx',引擎='xlsx

我刚刚开始学习python,我试图通过一个简单的
for
-循环从数组中传递一些术语,该循环使用基于正则表达式的模式进行搜索

ethnicities\u stems=[“宗教”、“天主教”、“抗议”]]
对于人种中的词干\u词干:
民族性\u模式=重新编译(r'.*.+词干+'.*'.')
种族=扩展.loc[lambda x:x['queryterm'].str.contains(种族模式,regex=True)]
writer=pd.ExcelWriter(词干+'.xlsx',引擎='xlsxwriter')
种族。到excel(书写者,工作表名称='Sheet1',索引=False)
writer.save()
印刷品(种族)
我在这里试图实现的是,循环将数组
religio
放入模式中,并将包含“cathol”或“displate”的所有数据提供给我,然后将它们一起写入一个新的
.xlsx


每次我尝试运行代码时,错误消息
TypeError:只能将str(而不是“list”)连接到str
提示。

错误是因为列表中的第二项是另一个列表(
[“cathol”,“displate”]
),无法添加到字符串中(就像您在
重新编译(r.*.+stem+.*)
中尝试做的那样)。我猜你可能会尝试这样做——创建一个名为“宗教”的Excel工作簿,其中包含名为“天主教”和“抗议”的表格

ethnicities_stemms = {"religion": ["cathol", "protest"]}

for key, value in ethnicities_stemms.items():
    # key is 'religion' and value is ['cathol', 'protest']
    writer = pd.ExcelWriter(key +'.xlsx', engine='xlsxwriter')
    for stemm in value:
        ethnicity_pattern = re.compile(r'.*'+stemm+'.*')
        ethnicity = expansions.loc[lambda x: x['queryterm'].str.contains(ethnicity_pattern, regex = True)]
        ethnicity.to_excel(writer, sheet_name=stemm, index=False)
        print(ethnicity)
    writer.save()

然后,您可以将其他键列表对添加到词典中。

尝试将
族裔词干=[“宗教”,“天主教”,“抗议”]
更改为
族裔词干=[“宗教”,“天主教”,“抗议”]
,看看是否会出现相同的错误。如果错误似乎与此无关,为什么标题会提到迭代?请提供完整的错误输出,以及。哦,不,但这不是我问题的解决方案。现在它运行了,但将“cathol”和“抗议”的数据写入了两个独特的excel表格,但我想实现的是,它将这两个数据写入了一个名为religionThank you的表格中!但可悲的是,它只是将“抗议”的数据写入表格,而忽略了“cathol”,这是因为它们在同一张表格中相互重叠。但是,我刚刚编辑过,所以它会创建单独的图纸。如果您想将两个表放在一张表上,您必须为
选择一个合适的
startrow
来定位它们,以便将
转换为excel
我很抱歉,您完全实现了我想要的目标。它在一个xlsx中创建了两张表。非常感谢你!!