简体   繁体   中英

Split string in a csv python

Every row of my list goes like this:

[(21, ['Rodriguez', 'Lara', 'Vicky', '55302292'])]

and I want it to print just the name, in this case Vicky . The code I use is this

for x in numbers:  
    r=str(x)  
    d1= r.split(',')  
    print ('D1', d1)  

and it prints this:

['[(21', " ['Rodriguez'", " 'Lara'", " 'Vicky'", " '55302292'])]"]

Don't turn your perfectly good list into a string! just use indexing:

x[0][1][2]

To illustrate what this does:

>>> x = [(21, ['Rodriguez', 'Lara', 'Vicky', '55302292'])]
>>> x[0]
(21, ['Rodriguez', 'Lara', 'Vicky', '55302292'])
>>> x[0][1]
['Rodriguez', 'Lara', 'Vicky', '55302292']
>>> x[0][1][2]
'Vicky'

Each additional subscription ( [...] ) drills deeper into the nested structure; x[0] extracts the tuple from the list; x[0][1] then accesses the list value in that tuple ( x[0][0] would give you 21 ), and x[0][1][2] give you back 'Vicky' , the third element in that nested list.

Get the list first, then extract data from it

>>> list = [(21, ['Rodriguez', 'Lara', 'Vicky', '55302292'])]
>>> names = list[0][1] 
>>> names
['Rodriguez', 'Lara', 'Vicky', '55302292']
>>> names[2]
Vicky

You can iterate over your list, while unpacking a tuple in each iteration. This would make it slightly more clean/readable.

>>> x = [(21, ['Rodriguez', 'Lara', 'Vicky', '55302292']), (22, ['Micheal', 'Jackson', 'John', '66302292'])]
>>> for age, details in x:
...     print details[2]
... 
Vicky
John

Try this:

for x in numbers:
  r=str(x)
  a=r.split(',')
  print (a[3].strip("' "))

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