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

How to distribute comma separated element to form a list in python

如何extract/split多行注释创建新列表

clientInfo="""James,Jose,664 New Avenue,New Orleans,Orleans,LA,8/27/200,123,jjose@gmail.com,;
  Shenna,Laureles, 288 Livinghood Heights,Brighton,Livingston,MI,2/19/75,laureles9219@yahoo.com,;
  """
 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"]

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

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])

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

你可以试试:

clientData = """James,Jose,664 New Avenue,New Orleans,Orleans,LA,8/27/200,123,jjose@gmail.com,;
  Shenna,Laureles, 288 Livinghood Heights,Brighton,Livingston,MI,2/19/75,laureles9219@yahoo.com,;
  """
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']

您可以使用 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', 'laureles9219@yahoo.com'), ('jjose@gmail.com', '')]

最后有一些元组不是你要的,但还是比较不错的。 no_space 第 1 行和第 2 行有点重复,但我认为将它们塞进一行更糟糕。