如何编写一个分隔逗号字符上每一行的函数?

Eri*_*iri 0 python split

例如:

Myfunction("1,2,3\n4,5,6")
Run Code Online (Sandbox Code Playgroud)

输出将是 [["1","2","3"],["4","5","6"]]

Mar*_*ers 7

使用列表理解:

def myfunction(somestring):
    return [line.split(',') for line in somestring.split('\n')]
Run Code Online (Sandbox Code Playgroud)

演示:

>>> def myfunction(somestring):
...     return [line.split(',') for line in somestring.split('\n')]
... 
>>> myfunction("1,2,3\n4,5,6")
[['1', '2', '3'], ['4', '5', '6']]
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用str.splitlines(),它可以正常工作,.split()但会将数据拆分到任何换行符上\r,\n或者\r\n.它处理最后一行也更聪明一些.

如果此数据来自文件,请考虑使用正确的工具; 该csv模块可以更好地处理以逗号分隔数据引用的复杂性:

import csv

with open('/your/csv/file.csv', 'rb') as inputfile:
    reader = csv.reader(inputfile)
    for row in reader:
        # row is a list of column values
Run Code Online (Sandbox Code Playgroud)

该数据不具有来自一个文件,csv可以处理任何可迭代的,包括的结果.splitlines():

reader = csv.reader(somestring.splitlines())
for row in reader:
    # row is a list of column values
Run Code Online (Sandbox Code Playgroud)