如何在python中分配逗号分隔的元素以形成列表

问题描述 投票:0回答:3

如何提取/分割多行注释以创建新列表

clientInfo="""James,Jose,664 New Avenue,New Orleans,Orleans,LA,8/27/200,123,[email protected],;
  Shenna,Laureles, 288 Livinghood Heights,Brighton,Livingston,MI,2/19/75,[email protected],;
  """
 into this kind of list

 f_name = ["james","sheena"]
 l_name = ["jose","Laureles"]
 strt = ["664 New Avenue","288 Livinghood Heights"]
 cty = ["New Orleans","Brighton"]
 state = ["New Orleans","Livingston"]
python string list split multiline
3个回答
0
投票

如果顺序始终相同。你可以做这样的事情;

f_name = []
l_name = []
strt = []
cty = []
state = []
for client in clientData.split(";\n "):
    client_ = client.split(",")
    f_name.append(client_[0])
    l_name.append(client_[1])
    strt.append(client_[2])
    cty.append(client_[3])
    state.append(client_[4])

我可以在字符串的末尾添加一些异常处理来处理;,但留给您。


0
投票

您可以使用splitzip

def extract(string):
  lines = string.split(";")
  split_lines = tuple(map(lambda line: line.split(","), lines))
  no_space1 = tuple(map(lambda item: item.strip(), split_lines[0]))
  no_space2 = tuple(map(lambda item: item.strip(), split_lines[1]))
  return list(zip(no_space1, no_space2))

将产生

[('James', 'Shenna'), ('Jose', 'Laureles'), ('664 New Avenue', '288 Livinghood Heights'), ('New Orleans', 'Brighton'), ('Orleans', 'Living
ston'), ('LA', 'MI'), ('8/27/200', '2/19/75'), ('123', '[email protected]'), ('[email protected]', '')]

它的末尾有一些您不需要的元组,但是它相对不错。no_space1行和2行有些重复,但是我认为将它们塞成一行比较糟糕。


0
投票

您可以尝试:

clientData = """James,Jose,664 New Avenue,New Orleans,Orleans,LA,8/27/200,123,[email protected],;
  Shenna,Laureles, 288 Livinghood Heights,Brighton,Livingston,MI,2/19/75,[email protected],;
  """
data = clientData.split(";\n")

f_name = []
l_name = []
strt = []
cty = []
state = []

for data_line in data:
    data_line = data_line.strip()
    if len(data_line) >= 5:
        line_info = data_line.split(",")
        f_name.append(line_info[0].strip())
        l_name.append(line_info[1].strip())
        strt.append(line_info[2].strip())
        cty.append(line_info[3].strip())
        state.append(line_info[4].strip())

print(f_name)
print(l_name)
print(strt)
print(cty)
print(state)

输出:

['James', 'Shenna']
['Jose', 'Laureles']
['664 New Avenue', '288 Livinghood Heights']
['New Orleans', 'Brighton']
['Orleans', 'Livingston']
© www.soinside.com 2019 - 2024. All rights reserved.