【问题标题】:Not able to get the desired output from the given code?无法从给定的代码中获得所需的输出?
【发布时间】:2020-09-18 07:46:59
【问题描述】:
lst = [["hi", "bye"], "hello", "goodbye", [9, 2], 4]
greeting_doubled = []
def f(g):
    return 2*lst
greeting_doubled = map(f,lst)
print(greeting_doubled)

预期:

[['hi','bye','hi','bye'], 'hellohello', 'goodbyegoodbye',[9,2,9,2], 8]

【问题讨论】:

  • 请格式化您的代码,您可以查看格式化规则here

标签: python python-3.x function dictionary oop


【解决方案1】:

您的代码有 2 个问题

  1. 在函数f(g) 中,您返回的是2*lst 而不是2*g
  2. map 返回一个生成器,因此要转换为列表,您必须使用 list(generator..)

更新代码:

lst = [["hi", "bye"], "hello", "goodbye", [9, 2], 4]
def f(g):
    return 2*g
getting_doubled = list(map(f,lst))
print(getting_doubled)

输出:

[['hi', 'bye', 'hi', 'bye'], 'hellohello', 'goodbyegoodbye', [9, 2, 9, 2], 8]

【讨论】:

    猜你喜欢
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 2021-05-12
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多