Python how to read multiple inputs in a same line [closed]
I want to know how can we read multiple input like ["a","b","c"] and sto开发者_如何转开发re it in same variable. I want to store a , b ,c as a separate input to a variable. thanx
How about this:
a, b, c = ["a", "b", "c"]
That assigns three new variables. If you want to operate on each in turn, use this instead:
for character in ['a', 'b', 'c']:
print character # prints 'a', then 'b', then 'c'.
If you are actually getting input from stdin or from a file, then it is as easy as using the split() function
f=open( 'myfile.txt', 'r')
for line in f.readlines():
# suppose line is '["a","b","c"]'
a = line.split( ',' )
# a is now the list [ '["a"', '"b"', '"c"]' ]
# To strip away the brackets use this instead:
a = line.strip('[]').split( '[]' )
# a is now the list [ '"a"', '"b"', '"c"' ]
# To strip away the spurious quote marks use this instead:
a = [ s.strip('"') for s in line.strip('[]').split(',') ]
# a is now the list [ 'a', 'b', 'c' ]
Of course, you could roll this into a single list comprehension:
lines = [ s.strip('"') for s in l.strip('[]').split(',') for l in open( 'myfile.txt', 'r' ).readlines() ]
I think that should work...I didn't check it in an interpreter. The idea here is to give you an idea of how you can roll together Pythons very powerful list processing functions with its equally awesome string processing functions.
Remember, read documentation!
Good Luck!
You can unpack iterables:
a, b, c = ['a', 'b', 'c']
精彩评论