gpt4 book ai didi

Python if/else 语句混淆

转载 作者:太空宇宙 更新时间:2023-11-03 21:45:52 24 4
gpt4 key购买 nike


当你有一个同时包含文本和数字的文件时,如何在 python 中创建 if else 语句。
假设我想替换下面文件中第三列到最后一列的值。我想创建一个 if else 语句来替换值 <5 或如果有一个点“.”为零,如果可能的话,使用该值作为总和的整数。
使用 awk 的快速而肮脏的解决方案如下所示,但我很好奇如何使用 python 处理此类数据:

 awk -F"[ :]" '{if ( (!/^#/) && ($9<5 || $9==".") ) $9="0" ; print }'

那么如何解决这个问题呢?
谢谢

输入文件:

\##Comment1
\#Header
sample1 1 2 3 4 1:0:2:1:.:3
sample2 1 4 3 5 1:3:2:.:3:3
sample3 2 4 6 7 .:0:6:5:4:0



期望的输出:

\##Comment1
\#Header
sample1 1 2 3 4 1:0:2:0:0:3
sample2 1 4 3 5 1:3:2:0:3:3
sample3 2 4 6 7 .:0:6:5:4:0
SUM = 5


到目前为止的结果

['sample1', '1', '2', '3', '4', '1', '0', '2', '0', '0', '3\n']
['sample2', '1', '4', '3', '5', '1', '3', '2', '0', '3', '3\n']
['sample3', '2', '4', '6', '7', '.', '0', '6', '5', '4', '0']


这是我到目前为止所尝试过的:

import re

data=open("inputfile.txt", 'r')
for line in data:
if not line.startswith("#"):
nodots = line.replace(":.",":0")
final_nodots=re.split('\t|:',nodots)
if (int(final_nodots[8]))<5:
final_nodots[8]="0"
print (final_nodots)
else:
print(final_nodots)

最佳答案

data=open("inputfile.txt", 'r')

import re
sums = 0
for line in data:
if not line.startswith("#"):
nodots = line.replace(".","0")
final_nodots=list(re.findall('\d:.+\d+',nodots)[0])
if (int(final_nodots[6]))<5:
final_nodots[6]="0"
print(final_nodots)
sums += int(final_nodots[6])
print(sums)

你已经非常接近了,但是你的final_nodots返回了:上的分割,而不是前几个数字的分割,所以你的8应该是一个 3.。之后,只需添加一个 sums 计数器来跟踪该插槽。

['sample1 1   2   3   4   1', '0', '2', '0', '0', '3\n']

有更好的方法来实现你想要的,但我只是想修复你的代码。

关于Python if/else 语句混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52505798/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com