我正在阅读带有'n'no的制表符分隔文件。对每行进行一些计算并将其打印到控制台。我面临的问题是某些行中的某些属性没有值并且具有空字符串。我想识别这样的空字符串并用零替换它们。这是我的代码和示例输入,如下所示。
代码: -
<p>
<!-- there is content omitted for brevity -->
<span data-ng-repeat="life in data.list2 track by $index">
<a class="pointer" ng-if="life.beneficiary.length > 0" ng-click="c.editBeneficiary(life)">
<!-- content omitted for brevity-->
</a>
<a class="pointer" ng-if="!life.beneficiary.length" ng-click="c.addBeneficiary()">Add Beneficiary </a>
</span>
</p>
输入: -
from datetime import datetime
import csv
with open('input1.txt') as inputfile:
reader = csv.reader(inputfile,delimiter='\t')
inputm = list(reader) #contents of csv
for i in inputm[1:]:
print('\n',str(datetime.strptime(i[0].split(':')[1], '%Y%m%d'))[:10] ,i[1],sum(map(float,i[2:6]))/4,i[6])
评论: - 第6行在第5个字段中有空格。需要识别这些字段并将其替换为零。
答案 0 :(得分:2)
您可以使用列表推导来执行此操作,该列表推导允许您执行if / else条件。作为测试
$Users = gc "C:\scripts\Users.txt"
$ADusers = Get-ADUser -Filter '*' -Properties DisplayName,SamAccountName,Enabled,MemberOf,PasswordNeverExpires,LockedOut |
select DisplayName, SamAccountName, Enabled, MemberOf, PasswordNeverExpires, LockedOut
$ADusers |
? { $Users -contains $_.SamAccountName } |
Out-File c:\scripts\results\UserResults.txt
Compare-Object $ADusers.SamAccountName $users |
? {$_.SideIndicator -eq =>} |
Select-Object -ExpandProperty InputObject |
Out-File c:\scripts\results\Failures.txt
将它放入你的代码中
>>> i = ['11', '', '3.3', '']
>>> sum(float(v) if v else 0.0 for v in i)
14.3
<强>更新强>
使用制表符显示示例可能很困难,因为stackoverflow会过滤掉它们。一种技术是编写一些将字节写入测试文件的代码,以便其他人可以运行它。下面是一个工作示例,显示from datetime import datetime
import csv
with open('input1.txt') as inputfile:
reader = csv.reader(inputfile,delimiter='\t')
inputm = list(reader) #contents of csv
for i in inputm[1:]:
print('\n', str(datetime.strptime(i[0].split(':')[1], '%Y%m%d'))[:10],
i[1], sum(float(v) if v else 0.0 for v in i[2:6])/4,i[6])
模块如何识别最后一行中有一个空制表符分隔的单元格,并用空字符串替换它。转换工作正常!
csv
输出:
# write a test file we can work with
open('mytest.csv', 'wb').write(
b"""1:20150501\t123\t10\t20\t0\t0\t'xyz'
2:20150501\t124\t0\t20.6\t90\t18.7\t'abc'
3:20150501:replacement\t123\t10.9\t20.3\t0\t80\t'def'
4:20150501\t134\t10\t20\t50.6\t0\t'ghi'
5:20150501\t126\t10.7\t26.8\t0\t0\t'jkl'
6:20150501\t123\t8.9\t20\t0\t\t'mno'""")
import csv
with open('mytest.csv', newline='') as fp:
reader = csv.reader(fp, delimiter='\t', skipinitialspace=True)
for row in reader:
converted = [float(v) if v else 0.0 for v in row[1:5]]
print(row, converted)
答案 1 :(得分:0)
你不能只使用循环和条件吗?
for idx, val in enumerate(i)
if i[idx].isspace():
i[idx] = 0
这将进入你的'line'循环
for i in inputm[1:]:
for idx, val in enumerate(i)
if i[idx].isspace():
i[idx] = 0
print('\n',str(datetime.strptime(i[0].split(':')[1], '%Y%m%d'))[:10] ,i[1],sum(map(float,i[2:6]))/4,i[6])