在字典列表中用 x 替换逗号 (Python)

我的代码:


for i in range(len(new_list)):

    # Use of Lambda to multiply each number in each list

    nums_product = reduce((lambda x,y: x * y), new_list[i])

    list_product_num.append(nums_product)

print(list_product_num)

x = [{'qns': f , 'ans': c} for f, c in zip(input_list, list_product_num)]

print(x, end= '' )enter code here

这是输出:


[{'qns': [1, 3, 3], 'ans': 9}, {'qns': [2, 5, -1], 'ans': -10}, {'qns': [3, 2], 'ans': 6}, {'qns': [4, 5, 3], 'ans': 60}, {'qns': [0, 23], 'ans': 0}, {'qns': [1, 2, 3, 4], 'ans': 24}]

然而,这是我必须实现的预期输出,基本上将 [1,3,3] 替换为“1 x 3 x 3”:


[{'qns': '1 x 3 x 3', 'ans': 9}, {'qns': '2 x 5 x -1', 'ans': -10}, {'qns': '3 x 2', 'ans': 6}, {'qns': '4 x 5 x 3', 'ans': 60}, {'qns': '0 x 23', 'ans': 0}, {'qns': '1 x 2 x 3 x 4', 'ans': 24}]

我一直在寻找解决这个问题的方法,如果有人能指出正确的方向,我将不胜感激,谢谢!


开满天机
浏览 52回答 3
3回答

尚方宝剑之说

您可以通过以下方式修改最终输出:x = [{'qns': ' x '.join(map(str, d['qns'])), 'ans': d['ans']} for d in x]如果您想从头开始构建正确的输出,只需将最后一行代码替换为:x = [{'qns': ' x '.join(map(str, f)) , 'ans': c}      for f, c in zip(input_list, list_product_num)]

宝慕林4294392

您正在寻找名为 的字符串的内置方法join。 " x ".join(f)但不起作用,因为列表中的项目f不是strings。为了解决这个问题,我们可以将列表中的每个项目转换为具有列表理解的字符串[str(n) for n in f]:将其放在一起作为您的示例,我们可以替换'qns': f为'qns': ' x '.join([str(n) for n in f])您没有为输入列表提供值,但我猜您唯一的输入是包含数字的列表列表。我冒昧地为您创建了一个紧凑的示例from functools import reducenew_list = [[1, 3, 3], [2, 5, -1], [3, 2], [4, 5, 3], [0, 23], [1, 2, 3, 4]]print([{"qns": " x ".join(str(x) for x in l), "ans": reduce((lambda x, y: x * y), l)} for l in new_list])>>> [{'qns': '1 x 3 x 3', 'ans': 9}, {'qns': '2 x 5 x -1', 'ans': -10}, {'qns': '3 x 2', 'ans': 6}, {'qns': '4 x 5 x 3', 'ans': 60}, {'qns': '0 x 23', 'ans': 0}, {'qns': '1 x 2 x 3 x 4', 'ans': 24}]

慕无忌1623718

替换f为以下内容:' x '.join([str(num) for num in f])结果会是这样的:x = [{'qns': ' x '.join([str(num) for num in f]) , 'ans': c} for f, c in zip(input_list, list_product_num)]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python