如何移除filter_col列表元素的括号与引号,输出纯字符串内容
问题原因
你当前代码中append()传入的是列表推导返回的列表对象,因此filter_col会成为嵌套列表,输出时才会带有外层方括号和多余引号。
解决方案
根据你的使用场景可选两种修改方式:
方式1:确认每个前缀仅匹配1个列(和你示例场景匹配)
直接取列表推导结果的第一个元素追加到filter_col中即可避免嵌套:
treated_sample = ["RP026_IP_1_S9_L001_R1_001", "RP026_IP_2_S10_L001_R1_001", "RP026_IP_3_S11_L001_R1_001", "RP026_IP_4_S12_L001_R1_001"] filter_col = [] for i in treated_sample: filter_col.append([col for col in df if col.startswith(i)][0]) # 输出纯字符串格式 for s in filter_col: print(s)
方式2:兼容一个前缀匹配多个列的情况
用extend()替代append(),会把匹配到的所有列名逐个加入filter_col,不会产生嵌套结构:
treated_sample = ["RP026_IP_1_S9_L001_R1_001", "RP026_IP_2_S10_L001_R1_001", "RP026_IP_3_S11_L001_R1_001", "RP026_IP_4_S12_L001_R1_001"] filter_col = [] for i in treated_sample: filter_col.extend([col for col in df if col.startswith(i)]) # 输出纯字符串格式 for s in filter_col: print(s)
两种方式执行后打印的结果都符合你需要的纯字符串换行格式。
内容的提问来源于stack exchange,提问作者xedahod951
相关产品推荐
相关产品推荐

