我是 python 新手,試圖弄清楚如何將 3 個由空格分隔的字串作為輸入,然后前兩個將是所需字典的鍵,而第三個字串將是鍵:
例子:
John Smith 1234
Mike Tyson 5678
字典應該是這樣的:
{'John Smith': '1234', 'Mike Tyson': '5678'}
如果它只是兩個非常簡單的字串,我得到了正確的答案:
count=int(input())
d=dict(input().split() for x in range(count))
print(d)
uj5u.com熱心網友回復:
您可以rsplit使用maxsplit=1; 這樣,你只從右邊分裂一次:
lst = ['John Smith 1234', 'Mike Tyson 5678']
d = {}
for string in lst:
s = string.rsplit(maxsplit=1)
d[s[0]] = s[1]
輸出:
{'John Smith': '1234', 'Mike Tyson': '5678'}
uj5u.com熱心網友回復:
# generator to yield input until an empty string is entered
def get_input():
s = input()
while s:
yield s
s = input()
# get input from the generator, split at the last " " and make a dict from it
d = dict(line.rsplit(maxsplit=1) for line in get_input())
在開始時選擇回圈數的函式:
def get_input():
count = int(input("how many entries: "))
for _ in range(count):
yield input()
uj5u.com熱心網友回復:
您可以使用 rsplit 最后一項。
count = int(input("How many times data you want to enter: "))
data_list = [input("Please enter the {} data: ".format(x 1)) for x in range(count)]
output_dict = dict(item.rsplit(' ', 1) for item in data_list)
print("Output:\n", output_dict)
>>
輸出:
How many times data you want to enter: 2
Please enter the 1 data: John Smith 1234
Please enter the 2 data: Mike Tyson 5678
Output:
{'John Smith': '1234', 'Mike Tyson': '5678'}
uj5u.com熱心網友回復:
可以使用str.rpartition(). 這將回傳前兩個字串、空格和最終字串的元組。(Python 3.10)
s = input()
key, space, final = s.rpartition(' ')
d = {key:final}
uj5u.com熱心網友回復:
假設字串輸入固定為 = 3,并且您要將字串接收到串列中:
from functools import reduce
S = ["John Smith 1234", "Mike Tyson 5678"]
reduce(lambda x,y: dict(x, **y), [dict([[" ".join(s.split()[:2]),s.split()[-1]]]) for s in S])
>> {'John Smith': '1234', 'Mike Tyson': '5678'}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/412417.html
標籤:
