简体   繁体   English

如何使用包含字符位置的字典在Python中切片?

[英]How to slice a string in Python using a dictionary containing character positions?

I have a dictionary containing the character positions of different fields in a string. 我有一个包含字符串中不同字段的字符位置的字典。 I'd like to use that information to slice the string. 我想用这些信息来切割字符串。 I'm not really sure how to best explain this, but the example should make it clear: 我不太确定如何最好地解释这一点,但这个例子应该说清楚:

input: 输入:

mappings = {'name': (0,4), 'job': (4,11), 'color': (11, 15)}
data = "JohnChemistBlue"

desired output: 期望的输出:

{'name': 'John', 'job': 'Chemist', 'color': 'Blue'}

Please disregard the fact that jobs, colors and names obviously vary in character length. 请忽略这样一个事实:工作,颜色和名字的字符长度明显不同。 I'm parsing fixed-length fields but simplified it here for illustrative purposes. 我正在解析固定长度的字段,但为了说明目的将其简化。

>>> dict((f, data[slice(*p)]) for f, p in mappings.iteritems())
{'color': 'Blue', 'job': 'Chemist', 'name': 'John'}
dict([(name, data[range[0]:range[1]]) for name, range in mappings.iteritems()])
>>> dict([(k, data[ mappings[k][0]:mappings[k][1] ]) for k in mappings])
{'color': 'Blue', 'job': 'Chemist', 'name': 'John'}

or with a generator instead of a list (probably more efficient): 或使用生成器而不是列表(可能更高效):

>>> dict(((k, data[ mappings[k][0]:mappings[k][1] ]) for k in mappings))
{'color': 'Blue', 'job': 'Chemist', 'name': 'John'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM