数组python,将输入字符串更改为List并在中输出

2024-05-23 19:53:48 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能帮我解决我的问题吗? 问题是

如果iam输入int(1,2,3,4,5,6,7,8,9,0)总是错误?你知道吗

data = input()

array = list(data)

table = {" ":270,
         "a":0,
         "b":90,
         "c":180,
         "d":270,
         "e":0,
         "f":90,
         "g":180,
         "h":270,
         "i":0,
         "j":90,
         "k":180,
         "l":270,
         "m":0,
         "n":90,
         "o":180,
         "p":270,
         "q":0,
         "r":90,
         "s":180,
         "t":270,
         "u":0,
         "v":90,
         "w":180,
         "x":270,
         "y":0,
         "z":90,
         "0":180,
         "1":270,
         "2":0,
         "3":90,
         "4":180,
         "5":270,
         "6":0,
         "7":90,
         "8":180,
         "9":270,
         "!":0,
         "@":90,
         "#":180,
         "$":270,
         "%":0,
         "^":90,
         "&":180,
         "*":270,
         "(":0,
         ")":90,
         "-":180,
         "_":270,}



for i in range(len(array)):

    print(array[i])

    print(("{["+array[i]+"]}").format(table))

错误位置:

例如:如果am输入a#2

print(("{["+array[i]+"]}").format(table))

KeyError: 2

Tags: informatforinputdatalen错误table
3条回答

不幸的是,您不能使用整数作为格式语言中element_index字典的字符串键。这是格式语言的一个限制,它将整数element_index视为整数。不幸的是,除了说:

element_index ::= integer | index_string

>>> "{[2]}".format({'2':0})
KeyError: 2
>>> "{[*]}".format({'*':0})
'0'
>>> "{[2]}".format({2:0})
'0'

我想你也会得到同样的结果

data = input()

for char in data:
    print(char)
    print(table[char])

field_name的文档中:

The field_name itself begins with an arg_name that is either a number or a keyword. If it’s a number, it refers to a positional argument, ...

以及

Because arg_name is not quote-delimited, it is not possible to specify arbitrary dictionary keys (e.g., the strings '10' or ':-]') within a format string.

字段名称的语法规范如下所示

field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*

我认为括号/方括号表示arg\u名称可以是dotAttribute或索引表达式,[2],因此形式'10'限制的任意字典键适用-如果这是正确的,那么文档可能更清晰。你知道吗

>>> d
{'1': 123, 'a': 4}

使用'''{['1']}'''作为格式字符串,返回一个不起作用的双引号字符串。你知道吗

>>> '''{['1']}'''.format(d)
Traceback (most recent call last):
  File "<pyshell#98>", line 1, in <module>
    '''{['1']}'''.format(d)
KeyError: "'1'"

>>> d.__getitem__("'1'")
Traceback (most recent call last):
  File "<pyshell#100>", line 1, in <module>
    d.__getitem__("'1'")
KeyError: "'1'"

然后对格式字符串使用''{a2}}''创建一个整数,该整数被传递给__getitem__

>>> '''{[1]}'''.format(d)
Traceback (most recent call last):
  File "<pyshell#101>", line 1, in <module>
    '''{[1]}'''.format(d)
KeyError: 1
>>>

.format就是不能将一个看起来像'2'的字符串传递给__getitem__


如果字典有一个双引号键,那么它就工作了

>>> d["'1'"] = 'foo'
>>> d
{'1': 123, "'1'": 'foo', 'a': 4}
>>> "{['1']}".format(d)
'foo'
>>>

相关问题 更多 >