簡體   English   中英

將列表作為用戶的輸入

[英]Taking a list as input from user

在將列表作為用戶的輸入時,輸入應該包含在方括號中,而不是僅僅輸入數字 這是我從用戶那里獲取多個輸入以獲取列表的代碼

a = list(map(int,input().strip().split(', ')))

默認輸入為 [1, 2, 3, 4]。 當我運行我的代碼時,我得到一個錯誤:

ValueError: invalid literal for int() with base 10: '[1'

我知道它發生的原因是因為 '[1' 是一個無法轉換為 int 的元素,它(方括號和 1)被視為索引 0 處列表的第一個元素。方括號是對我來說絕對必要,我該如何解決錯誤或忽略方括號? 是否有可能有效的忽略方法或類似方法? 干杯!

從輸入中去掉括號:

a = [int(n) for n in input().strip('[]').split(',')]

您可以在將其轉換為 int 之前將其從字符串中刪除:

a = list(map(int,
             input()
             .strip()
             .replace('[', '')
             .replace(']', '')
             .split(', ')
            )
        )

或者您也可以使用正則表達式來獲取所有數字:

import re
a = list(map(int, re.findall(r'\d+', input())))

以一種簡單的方式,您可以使用 strip() 刪除多余的空格和 '[ ]'。

a = list(map(int, input().strip(' []').split(',')))

暫無
暫無

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

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