简体   繁体   中英

Insert splitted string into a list in python

consider this piece of code:

csvreader = csv.reader(filter(lambda row: row[0] != '#', fcsv), delimiter= '\t')
csvrs =[[row[2], row[7]] for row in csvreader]

the element row[7] is a string separated by ; , what i want to do is not put the entire row[7] inside csvrs but only a splitted part seaprated by ; Say for example:

row[7] = '123;457;789;1011'

i want only the second position inside csvrs (in this case 457) and i want this every time filtering out every other piece. I'M trying with split with no result maintaining the list comprehension.

只需在理解内进行拆分,并获得第二项的[1]

csvrs =[[row[2], row[7].split(';')[1]] for row in csvreader]
def get_second_col(row, delimiter=';'):
    try:
        return row.split(delimeter)[1]
    except IndexError:
        return None

csvrs =[[row[2], get_second_col(row[7])] for row in csvreader]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM