2012-03-25 63 views
-1

如何,我可以通過蟒蛇 讀取一個行中鍵入兩個變量的兩個值,如%d%d在C 的raw_input在該行Python的輸入讀取格式

如1 0

我想讀的一切1 in x and 0 in y

回答

0

使用larsmans的方法已經足夠了。如果你真的想要scanf的東西,而且最重要的是,不想看整行。儘管如此,它可能會很慢。

import re 
import sys 

class Pin: 
    formatDict = {'%d': r'(\d+)', '%f': r'(\d+\.?\d*)'} 
    def __init__(self, input=sys.stdin): 
     self.input = input 

    def scanf(self, format): 
     # change the C style format to python regex 
     for a, b in self.formatDict.iteritems(): 
      format = format.replace(a, b) 
     patt = re.compile('^\\s*%s$'%format, re.M) 
     buf = '' 
     matched = 0 
     while 1: 
      c = self.input.read(1) 
      if not c: break 
      buf += c 
      g = patt.match(buf) 
      if g: 
       # matched, but there may be more to match, so don't break now 
       matched = 1 
       matchedGroup = g 
      elif matched: 
       # the first unmatch after a match, seek back one char and break now 
       self.input.seek(-1, 1) 
       break 
     if matched: 
      return tuple(eval(x) for x in matchedGroup.groups()) 

scanf = Pin(open('in', 'r')).scanf 
print scanf('%d %d') 
print scanf('%f %f') 

醜但有趣,對不對?

5
x, y = map(int, raw_input().split()) 
0

您可以閱讀整行並使用正則表達式來解析它。使用組來獲取有趣的部分。否則,只要使用string.split,如果你不需要這樣的控制。