提问人:M Raj 提问时间:10/10/2023 最后编辑:wimM Raj 更新时间:10/17/2023 访问量:72
用逗号拆分并忽略 if 逗号引用元组列表中的数据 - Python
split by comma and ignore if comma in quotes a data from List of Tuples - Python
问:
我有一个元组列表。
lt = [('051623', 'O143', '1.23', '2023-05-16T18:30:00', '1M allen', 'millan'), ('051623', 'O207', '1.23', '2023-05-16T18:35:00', 'nM Mn, 4nM, 35uM Fe', 'wilo')]
需要通过逗号分隔转换为csv字符串,但在拆分引号内的逗号时要忽略:预期如下。
'051623','O143','1.23','2023-05-16T18:30:00','1M allen','millan'
'051623', 'O207', '1.23', '2023-05-16T18:35:00','nM Mn, 4nM, 35uM Fe','wilo'
我试过了但没有工作:
csv_string = '\n'.join(",".join([element if element else 'None' for element in tup]) for tup in lt)
答:
4赞
enzo
10/10/2023
#1
您可以使用该库:csv
lt = [
('051623', 'O143', '1.23', '2023-05-16T18:30:00', '1M allen', 'millan'),
('051623', 'O207', '1.23', '2023-05-16T18:35:00', 'nM Mn, 4nM, 35uM Fe', 'wilo'),
]
import io
import csv
# Allows saving the csv output to a string instead of a file
f = io.StringIO(newline='')
writer = csv.writer(
f,
quotechar="'",
quoting=csv.QUOTE_ALL,
)
writer.writerows(lt)
# `getvalue()` returns a string containing the csv output
print(f.getvalue())
它输出
'051623','O143','1.23','2023-05-16T18:30:00','1M allen','millan'
'051623','O207','1.23','2023-05-16T18:35:00','nM Mn, 4nM, 35uM Fe','wilo'
0赞
nigh_anxiety
10/10/2023
#2
如果您只是尝试将行重构为 csv 数据而不实际写入 CSV,则可以使用以下命令,它将每个单独的值括在双引号中
lines=[]
for tup in lt:
lines.append('"' + '","'.join(tup)+'"')
print(lines)
# [
# '"051623","O143","1.23","2023-05-16T18:30:00","1M allen","millan"',
# '"051623","O207","1.23","2023-05-16T18:35:00","nM Mn, 4nM, 35uM Fe","wilo"'
# ]
或者,如果您只想换行包含逗号的单元格:
lines=[]
for tup in lt:
line=''
for el in tup:
if ',' in el:
el = '"'+el+'"'
line += el + ','
lines.append(line[:-1]) # Strip the extra , at the end
print(lines)
# [
# '051623,O143,1.23,2023-05-16T18:30:00,1M allen,millan',
# '051623,O207,1.23,2023-05-16T18:35:00,"nM Mn, 4nM, 35uM Fe",wilo'
# ]
1赞
Reilas
10/10/2023
#3
下面是一个示例。
s = '\n'.join([','.join([f"'{y}'" for y in x]) for x in lt])
输出
'051623','O143','1.23','2023-05-16T18:30:00','1M allen','millan'
'051623','O207','1.23','2023-05-16T18:35:00','nM Mn, 4nM, 35uM Fe','wilo'
此外,您需要对文本中的任何单引号进行转义。
s = '\n'.join([','.join([f"'{y}'" for y in [z.replace("'", r"\'") for z in x]]) for x in lt])
0赞
XMehdi01
10/16/2023
#4
我的代码遍历列表,通过在元组中添加单引号来格式化元组中的每个元素,并用逗号连接它们。如您的问题中所述:lt
lt = [
("051623", "O143", "1.23", "2023-05-16T18:30:00", "1M allen", "millan"),
("051623", "O207", "1.23", "2023-05-16T18:35:00", "nM Mn, 4nM, 35uM Fe", "wilo"),
]
for words in lt:
formatted_words = []
for word in words:
formatted_word = "'{}'".format(word)
formatted_words.append(formatted_word)
formatted_lt = ",".join(formatted_words)
print(formatted_lt)
评论