【问题标题】:Map List into Tuples?将列表映射到元组?
【发布时间】:2015-07-14 13:27:54
【问题描述】:

我正在尝试将行列表映射到具有行号和行长的元组。我的指令要求我在 Python 中使用 map、filter 和 reduce 功能。

到目前为止,我已经有了过滤器,就在这里。

def code_metric(file):
    x = filter(lambda x : x != "\n", open(file))
    y = map(lambda x: )

它应该是什么样子的示例......

(1,行中的字符数)

我无法使用 map 函数将列表映射到行号和行长。

【问题讨论】:

  • 你想计算一行的长度并将其存储在一个带有迭代次数的元组中吗?
  • 是的。到目前为止我已经得到了这个...... tester = map(lambda x : (x[0] + 1, len(x[1])), enumerate(txt))
  • @Xari 查看我的解决方案

标签: python lambda mapping tuples iterable


【解决方案1】:
def code_metric(file):
    with open(file, 'r') as f:
        metric = list(enumerate(map(len, f), 1))
    return metric

这个函数会做你想做的事。您能否解释一下lambdareduce 与此功能有何关联?

【讨论】:

    【解决方案2】:

    这是在你们的回答帮助我推断出来之后我最终得到的解决方案。

    filtered = map(lambda x : (1, len(x.strip('\n'))), mapper)
    

    元组中的第一个值应该是默认的“1”(对不起!)

    【讨论】:

      【解决方案3】:

      试试这样:

      map(lambda x:(x[0], len(x[1])), enumerate(open('your_file'), start=1))
      

      【讨论】:

        猜你喜欢
        • 2016-07-31
        • 2015-04-30
        • 1970-01-01
        • 2011-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-28
        • 1970-01-01
        相关资源
        最近更新 更多