本文介绍了使用输入值在Python中创建字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎简单但难以捉摸,想仅使用一个Python语句根据由空格分隔的[键,值]对的输入来构建字典.这是我到目前为止的内容:

Seems simple, yet elusive, want to build a dict from input of [key,value] pairs separated by a space using just one Python statement. This is what I have so far:

d={}
n = 3
d = [ map(str,raw_input().split()) for x in range(n)]
print d

输入:

A1023 CRT
A1029 Regulator
A1030 Therm

所需的输出:

{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}

推荐答案

使用str.splitines()str.split():

In [126]: strs="""A1023 CRT
   .....: A1029 Regulator
   .....: A1030 Therm"""

In [127]: dict(x.split() for x in strs.splitlines())
Out[127]: {'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}

返回S中的行列表,在行边界处中断.线 除非给出保持符,否则中断不包括在结果列表中 是真的.

Return a list of the lines in S, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

str.split([sep [,maxsplit]])->字符串列表

str.split([sep [,maxsplit]]) -> list of strings

使用sep作为分隔符,返回字符串S中的单词列表 细绳.如果给出了maxsplit,则最多完成maxsplit分割.如果 sep未指定或为None,任何空格字符串都是分隔符 并将空字符串从结果中删除.

Return a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.

这篇关于使用输入值在Python中创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 11:34