展开嵌套的字符串列表并另存为.txt

时间:2019-04-06 21:09:23

标签: python list

我有一个包含字符串元素的列表:

$categoryId = $_REQUEST['category_id'];
$locationId = $_REQUEST['location_id'];
$statusId = $_REQUEST['status_id'];
// This can be done in different ways, I kept your "style" since you may have other reasons to extract the values
$arr =[$categoryId, $locationId, $statusId];

$arr = array_filter($arr); // remove empty values
$return[] = false; // set 0 key to false. First iteration will overwrite it
foreach($arr as $key => $val){
    if (isInTaxonomy($recordId, $val)) {
         $return[$key] = true;
    }
}

if(array_diff($return, [true])) {
    // Don't do something (?)
}else{
    // Do something
    // (All is true)
} 

我想以一行形式将其写入.txt文件:

[['110,67,169,86,5'], ['421,404,323,187,5'], ['865,98,452,53,2']]  

谢谢您的帮助!

2 个答案:

答案 0 :(得分:0)

如果输入正确:

>>> a = [['110,67,169,86,5'], ['421,404,323,187,5'], ['865,98,452,53,2']]
>>> " ".join([x[0] for x in a])
'110,67,169,86,5 421,404,323,187,5 865,98,452,53,2'


答案 1 :(得分:0)

展开您的值并将它们连接到一个字符串中

x = [['110,67,169,86,5'], ['421,404,323,187,5'], ['865,98,452,53,2']]
joined = ' '.join(sum(x, []))
# -> '110,67,169,86,5 421,404,323,187,5 865,98,452,53,2'

将结果保存到文件

file = open('unrolled.txt', 'w')
file.write(joined)
file.close()