如何在删除换行符的同时遍历dict?

2024-06-25 23:13:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试遍历字典并删除换行符,并且在解析条目时遇到困难。你知道吗

说我们有

line_contents = {"user_id": "6GrH6gp09pqYykGv86D6Dg", "text": "Decent selection of more than just bar food. \n\nJumbo fish sandwich is aptly named. \n\nSeem to be generous with the pour.", "business_id": "fNGIbpazjTRdXgwRY_NIXA", "likes": 0, "date": "2013-04-22", "type": "tip"}

#I've tried:
line_contents=dict(map(strip(),x) for x in line_contents.items())
#but ^ doesn't work. I can't figure out how the map function or the dictionary comprehension works

#I eventually want:
line_contents = {"user_id": "6GrH6gp09pqYykGv86D6Dg", "text": "Decent selection of more than just bar food. Jumbo fish sandwich is aptly named. Seem to be generous with the pour.", "business_id": "fNGIbpazjTRdXgwRY_NIXA", "likes": 0, "date": "2013-04-22", "type": "tip"}

我很想用一个典型的for循环遍历dictionary元素,但我想尝试dict理解,因为我从来没有这样做过。你知道吗


Tags: ofthetextidfoodmorelinecontents
2条回答

你可以使用dict理解,但由于你的一些值不是字符串,你必须考虑到这一点:

line_contents = {k: v.replace('\n', '') if isinstance(v, str) else v for k, v in line_contents.items()}

如果键和值都包含换行符,可以使用dict内置:

line_contents = dict([y.replace('\n', '') if isinstance(y, str) else y for y in x] 
                     for x in line_contents.items())

当然,听写理解仍然有效,但看起来相当混乱:

line_contents = {k: v for k, v in
                 ([y.replace('\n', '') if isinstance(y, str) else y for y in x]
                  for x in line_contents.items())
                 }

实际上,你不是在用字典。这是一个只有一个参数的函数调用:一个生成器表达式。词典理解更像这样:

line_contents = {key: value.replace("\n", "") for key, value in line_contents.items()}

编辑:niemmi很好地指出,值并不都是字符串。因此,你应该使用类似于他的建议:

line_contents = {k: v.replace("\n", "") if isinstance(v, basestring) else v for k,v in line_contents.items()}

我使用basestring而不是niemmi的str,因为它们实际上是unicode。在python3中,应该使用str。你知道吗

你的怎么了?好吧,你给了dict一个论点。考虑一下:

argument = []
for x in line_contents.items():
    argument.append(map(strip(), x))

line_contents = dict(argument)

这就是你正在做的。对于每个键值对,您将给map()两个参数strip()x。对于map(strip(), x)的一个调用,实际上是这样做的:

function = strip()
result = []
for item in x:
    result.append(function(item))

现在你必须明白问题所在。首先,没有定义strip。另一方面,应该为map提供函数,而不是函数返回的内容。如果您想使用str.strip,请这样做:

map(str.strip, x)

问题是,从末端的{{CD12}}条;它不移除中间出现的新行。你知道吗

相关问题 更多 >