【问题标题】:for loop through stdin using previous itemfor 循环使用上一项通过标准输入
【发布时间】:2019-01-16 20:58:28
【问题描述】:

我想将一行与前一行进行比较,而不在内存中存储任何内容(没有字典)。

样本数据:

a   2
file    1
file    2
file    4
for 1
has 1
is  2
lines   1
small   1
small   2
test    1
test    2
this    1
this    2
two 1

伪代码:

for line in sys.stdin:
    word, count = line.split()
    if word == previous_word:
        print(word, count1+count2)

我知道我会在数组上使用enumeratedict.iteritems,但我不能使用sys.stdin

期望的输出:

a   2
file    7
for 1
has 1
is  2
lines   1
small   3
test    3
this    3
two 1

【问题讨论】:

  • 可以重复2次以上吗?
  • 您需要将previous_word 分配给某事
  • 嗨,我编辑了我的问题,所以我正在寻找可能适用于超过 2 次重复但它们将彼此相邻的东西。我知道 previous_word 和 count1, count2 没有分配;我不确定我是否可以使这种方法起作用?
  • 所以是 Python 还是 bash?顺便说一句,你可以sys.stdin上使用enumerate
  • “我不确定我是否可以使这种方法工作” - 所以,试一试 - 将你的伪代码转换为代码 - 然后发布你的代码,实际输出和调试您尝试过;这将构成MCVE 的基础,这是关于 SO 的一个好问题

标签: python bash stdin sys


【解决方案1】:

基本逻辑是跟踪前一个单词。如果当前单词匹配,则累积计数。如果没有,打印前一个单词及其计数,然后重新开始。有一些特殊的代码来处理第一次和最后一次迭代。

stdin_data = [
    "a   2",
    "file    1",
    "file    2",
    "file    4",
    "for 1",
    "has 1",
    "is  2",
    "lines   1",
    "small   1",
    "small   2",
    "test    1",
    "test    2",
    "this    1",
    "this    2",
    "two 1",
]  

previous_word = ""
word_ct = 0

for line in stdin_data:
    word, count = line.split()
    if word == previous_word:
        word_ct += int(count)
    else:
        if previous_word != "":
            print(previous_word, word_ct)
        previous_word = word
        word_ct = int(count)

# Print the final word and count
print(previous_word, word_ct)

输出:

a 2
file 7
for 1
has 1
is 2
lines 1
small 3
test 3
this 3
two 1

【讨论】:

  • 我相信我在技术上领先你 6 秒。 +1 给你!
  • @MadPhysicist:当我发布时,刷新没有显示你的答案。网络滞后。 :-) 是的,+1 给你!
【解决方案2】:

您的代码几乎就在那里。虽然不想将整个内容存储在内存中是值得称赞的,但您必须存储上一行的累积组件:

prev_word, prev_count = '', 0
for line in sys.stdin:
    word, count = line.split()
    count = int(count)
    if word == prev_word:
        prev_count += count
    elif prev_count:
        print(prev_word, prev_count)
        prev_word, prev_count = word, count

【讨论】:

    【解决方案3】:

    我想将一行与前一行进行比较,而不在内存中存储任何内容(没有字典)。

    为了能够总结之前所有具有相似单词的行的计数,您需要保持一些状态。

    通常这个工作适合awk。你可以考虑这个命令:

    awk '{a[$1] += $2} p && p != $1{print p, a[p]; delete a[p]} {p = $1} 
    END { print p, a[p] }' file
    
    a 2
    file 7
    for 1
    has 1
    is 2
    lines 1
    small 3
    test 3
    this 3
    two 1
    

    使用delete,此解决方案不会将整个文件存储在内存中。状态仅在处理具有相同第一个单词的行期间保持。

    Awk 参考:

    【讨论】:

    • 谢谢?什么是 awk/我在哪里可以找到更多关于它的信息
    • 我在我的回答中添加了几个awk 引用
    猜你喜欢
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 2010-10-17
    • 2013-10-21
    相关资源
    最近更新 更多