[英]array python, input string change to List and output int
有人可以幫助我解決我的問題嗎? 問題是
如果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))
錯誤:
例如:如果輸入a#2
print(("{["+array[i]+"]}").format(table))
KeyError: 2
不幸的是,您不能將整數用作格式語言中element_index
字典的字符串鍵。 這是格式語言的局限性,它將整數element_index
視為整數。 不幸的是,文檔https://docs.python.org/3.5/library/string.html#formatspec中沒有明確指出,除了說:
element_index :: =整數| index_string
>>> "{[2]}".format({'2':0})
KeyError: 2
>>> "{[*]}".format({'*':0})
'0'
>>> "{[2]}".format({2:0})
'0'
從文檔中找到field_name :
field_name本身以數字或關鍵字arg_name開頭。 如果是數字,則表示位置參數 ...
和
由於arg_name不是用引號分隔的,因此無法在格式字符串中指定任意字典鍵(例如,字符串'10'或':-]')。
field_name的語法規范顯示為
field_name ::= arg_name ("." attribute_name | "[" element_index "]")*
我認為括號/括號中的內容是arg_name可以是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'"
然后使用'''{ 1 }'''作為格式字符串創建一個整數,該整數將傳遞給__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'
>>>
我想你得到相同的結果
data = input()
for char in data:
print(char)
print(table[char])
由於您的問題已得到回答,因此我想指出另一種方法,您可以將字符轉換為數字而無需花費很長時間。
chars = " abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_"
for char in chars:
print(char, (chars.index(char)+3)%4 * 90)
老實說,我認為原始方法可能會更好,因為它的作用非常明顯,但我只是想表明有一種更簡單的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.