Python 使用上一项通过标准输入进行循环
我想将一行代码与前一行代码进行比较,而不在内存中存储任何内容(没有字典) 样本数据:Python 使用上一项通过标准输入进行循环,python,bash,stdin,sys,Python,Bash,Stdin,Sys,我想将一行代码与前一行代码进行比较,而不在内存中存储任何内容(没有字典) 样本数据: 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 == pr
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)
我知道我会在数组上使用enumerate
或dict.iteritems
,但我不能在sys.stdin
上使用
期望输出:
a 2
file 7
for 1
has 1
is 2
lines 1
small 3
test 3
this 3
two 1
我想将一行代码与前一行代码进行比较,而不在内存中存储任何内容(没有字典)
为了能够用相似的单词总结前面所有行的计数,您需要维护一些状态
通常此作业适合于awk
。你可以考虑这个命令:
awk '{a[$1] += $2} p && p != $1{print p, a[p]; delete a[p]} {p = $1}
END { print p, a[p] }' file
使用delete
,此解决方案不会将整个文件存储在内存中。状态仅在处理具有相同第一个字的行时保持
Awk参考资料:
- 基本逻辑是跟踪上一个单词。如果当前单词匹配,则累积计数。如果没有,请打印上一个单词及其计数,然后重新开始。有一些特殊的代码来处理第一次和最后一次迭代
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
你的代码就快到了。虽然不想将整个内容存储在内存中是值得称赞的,但您必须存储前一行的累积组件:
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
可以有2次以上的重复吗?你需要给某个东西分配
上一个单词
。嗨,我编辑了我的问题,所以我想找一些可能适用于2次以上重复的东西,但它们将彼此相邻。我知道前面的单词和count1,count2没有赋值;但我不确定我是否能使这种方法起作用?所以它是Python还是bash?顺便说一句,您可以在sys.stdin
上使用enumerate“我不确定我是否可以让这种方法工作”——因此,尝试一下——将伪代码转换为代码——然后发布您的代码、实际输出和您尝试过的调试;这将构成a的基础,这是一个关于SOI的好问题,我相信我在技术上比你领先了6秒+祝你好运@物理学家:当我发布的时候,刷新并没有显示你的答案。网络延迟。:-)是的,给你+1!非常感谢。什么是awk/我在哪里可以找到更多关于itI的信息?我在回答中添加了两个awk
参考资料
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