简体   繁体   English

扁平化python中字符串列表的列表

[英]flatten list of list of strings in python

I have the following list in python: 我在python中有以下列表:

ipdb> xgboost_prediction
'[["2019-08-16 14:22:00.0", "ls5923_splunk", "False"]]'

and my goal is to append it to the csv file, which will happen on minute base. 而我的目标是将其附加到csv文件中,这将在一分钟内完成。

Now, I thought I would convert is easily to pandas dataframe and append csv. 现在,我想我可以轻松地将其转换为pandas dataframe并附加csv。 But somehow I am struggling with it. 但是不知何故我在为此挣扎。 How would I flatten it and convert to dataframe? 如何将其展平并转换为数据框?

I tried: 我试过了:

ipdb> 
ipdb> list2 = [inner for item in xgboost_prediction for inner in ast.literal_eval(item)]
*** SyntaxError: unexpected EOF while parsing

ipdb> new_lst = [sub_val for val in xgboost_prediction for sub_val in eval(val)]
*** SyntaxError: unexpected EOF while parsing

Please advice. 请指教。

Since you just want to append normally formatted values to a csv using pandas is overkill. 由于您只想使用熊猫将标准格式的值附加到csv,这是过分的。 You can simply convert your array to a comma separated string and append that to the file directly. 您只需将数组转换为逗号分隔的字符串,然后将其直接附加到文件中即可。 If you think your string might have special characters you can also use the csv library which will automatically add the proper formatting to escape any strings. 如果您认为字符串可能包含特殊字符,则还可以使用csv库,该库将自动添加正确的格式以转义任何字符串。

xgboost_prediction = [["2019-08-16 14:22:00.0", "ls5923_splunk", "False"]]

with open('outputfile.csv', 'a+') as f:
    # Incase you are appending multiple predictions
    for entry in xgboost_prediction:
        f.write(','.join(entry))
    f.write('\n')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM