簡體   English   中英

Python - 使用map存儲字符串和int(sys.stdin.readline())

[英]Python - store a string and an int using map(sys.stdin.readline())

如果輸入包含空格分隔的int行,則 -

1 3

我可以使用map()函數將它存儲在一個數組中

arr = map(int,sys.stdin.readline().split())

或者甚至在兩個單獨的變量中

n,m = map(int,sys.stdin.readline().split())

有沒有辦法使用相同的方法來讀取包含混合數據類型的輸入行。 例如。-

foo 3

其中foo是一個字符串, 3是一個整數?

要做到這一點,你應該能夠區分可以表示整數的字符串和不能表示整數的字符串。 一個例子是:

def foo(s):
    try:
        return int(s)
    except ValueError:
        return s

然后你通常可以使用map

map(foo, sys.stdin.readline().split())

以上輸入行:

abcdef 110

將打印:

['abcdef', 110]

如果你總是有一個字符串和非負int:

import sys
n, m = map(lambda x: (str, int)[x.isdigit()](x) ,sys.stdin.readline().split(None, 1)) 


print(n,m)

但最安全的方法是在使用try / except時,即使只是期望一種類型,也可以在轉換用戶輸入時使用。

根據要求,可以檢查否定:

import sys
n, m = map(lambda x: (str, int)[x.isdigit() or x.strip("-").isdigit()](x) ,sys.stdin.readline().split())


print(n, m)

但是--10-- --10 --10--也會通過測試,但只會因你的具體情況再次導致錯誤。

您可以使用str.isdigit來測試字符串是否可以轉換為整數。

>>> inpt = "foo 3"
>>> [int(s) if s.isdigit() else s for s in inpt.split()]

當然,你可以使用mapsys.stdin.readline使用lambda來做同樣的sys.stdin.readline

>>> map(lambda s: int(s) if s.isdigit() else s, sys.stdin.readline().split())
foo 4
['foo', 4]

如果要支持各種數據類型,可以嘗試使用literal_eval並回退到基本字符串(如果不起作用)。

import ast
def try_eval(string):
    try:
        return ast.literal_eval(string)
    except ValueError:
        return string

>>> map(try_eval, "42 3.14 foo 'bar' [1,2,3]".split())
[42, 3.1400000000000001, 'foo', 'bar', [1, 2, 3]]

map用於何時將相同的轉換應用於輸入的每個元素。 這不適合您的用例; 你想以不同的方式對待這兩個輸入。 由於數據具有固定格式的字符串,然后是整數,因此最好以始終生成該格式的方式對其進行解析:

x, y = raw_input().split()
y = int(y)

如果您有更多列,則可以列出用於處理每列的函數:

handlers = [str, int, int, str, float, int, int]
a, b, c, d, e, f, g = [f(x) for (f, x) in zip(handlers, raw_input().split())]

其他答案建議的解決方案不考慮輸入的固定格式。 如果用戶輸入

31 42

x應為"31" ,而不是31 ,如果用戶輸入

foo bar

應該被檢測為錯誤,而不是將"bar"分配給y

如果你沒有尋找任何花哨的東西,你可以快速“嘗試/除外”設置。

例如,

def convert(x):
    try:
        f = float(x)
        i = int(f)
        x = i if i == f else f
    except:
        pass
    return x

arr = map(convert, sys.stdin.readline().split())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM