开发者

Python how to read multiple inputs in a same line [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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']
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜