python 字典的值为列表,想把一个列表的值拼在一起用‘\t’隔开,变成一个字符串怎么写?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 字典的值为列表,想把一个列表的值拼在一起用‘\t’隔开,变成一个字符串怎么写?相关的知识,希望对你有一定的参考价值。
例如dic='name':['zhang','li','wang'],'sex':['male','female'],'sentence':['I am a student.','I like playing the piano.','I want to go out.']
然后我想合并成dic='name':['zhang li wang'],'sex':['male female']'sentence':['I am a student. I like playing the piano. I want to go out.]
中间合并后的空格是用'\t'隔开,即制表符隔开。
想用个for循环,然后用'\t'.join(),但是失败了
dic = 'name': ['zhang', 'li', 'wang'], 'sex': ['male', 'female'],'sentence': ['I am a student.', 'I like playing the piano.', 'I want to go out.']
str0 = ''
for i in dic:
for j in dic[i]:
str0 += j + '\\t'
str0 = str0.strip('\\t')
dic[i] = str0
str0 = ''
print(dic)
这里虽然打印出来带有\\t,但是实际上他就是制表符,我分别打印出值你看看:
参考技术A dic = 'name': ['zhang', 'li', 'wang'], 'sex': ['male', 'female'],'sentence': ['I am a student.', 'I like playing the piano.', 'I want to go out.']
d = k: [' '.join(v)] for k, v in dic.items()
print(d)
#'name': ['zhang li wang'], 'sex': ['male female'], 'sentence': ['I am a student. I like playing the piano. I want to go out.'] 参考技术B dic2=key:'\t'.join(value) for key,value in dic.items() 参考技术C 比∨
厂)∴
4947644786634886
替换 Python 列表/字典中的值?
【中文标题】替换 Python 列表/字典中的值?【英文标题】:Replacing values in a Python list/dictionary? 【发布时间】:2010-11-07 18:32:21 【问题描述】:好的,我正在尝试过滤传递给我的列表/字典并稍微“清理”一下,因为其中有一些我需要删除的值。
所以,如果它看起来像这样:
"records": ["key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"...]
如何快速轻松地完成所有操作并将“AAA”的所有值替换为“XXX”之类的值?
重点是速度和资源,因为这些可能很长,我不希望这个过程消耗太多时间。
【问题讨论】:
【参考方案1】:就我而言,在 字典理解 中使用 if/else 比上述答案快得多。在下文中,我为您的用例提供了一个通用示例:
DATA = "records_0": ["key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA",
"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"],
"records_1": ["key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"]
Replaced_DATA = k:[
k_0:v_0 if v_0!='AAA' else 'XXX' for k_0,v_0 in v_.items() for v_ in v] for k,v in DATA.items()
这是输出:
Replaced_DATA
Out[1]. 'records_0': ['key1': 'XXX', 'key2': 'BBB', 'key3': 'CCC', 'key4': 'XXX',
'key1': 'XXX', 'key2': 'BBB', 'key3': 'CCC', 'key4': 'XXX'],
'records_1': ['key1': 'XXX', 'key2': 'BBB', 'key3': 'CCC', 'key4': 'XXX']
【讨论】:
【参考方案2】:DATA = "records": ["key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"]
for name, datalist in DATA.iteritems(): # Or items() in Python 3.x
for datadict in datalist:
for key, value in datadict.items():
if value == "AAA":
datadict[key] = "XXX"
print (DATA)
# Prints 'records': ['key3': 'CCC', 'key2': 'BBB', 'key1': 'XXX', 'key4': 'XXX']
【讨论】:
是的,这就像一个魅力。我错过了一个外部循环并收到 list/items() 错误...谢谢!【参考方案3】:dic = root['records'][0]
for i, j in dic.items(): # use iteritems in py2k
if j == 'AAA':
dic[i] = 'xxx'
【讨论】:
以上是关于python 字典的值为列表,想把一个列表的值拼在一起用‘\t’隔开,变成一个字符串怎么写?的主要内容,如果未能解决你的问题,请参考以下文章