使用if语句传递变量或python的其他函数

2024-04-28 04:55:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一名生物学家,正试图使用python自动化大量计算,所以我的经验很少

我有一个非常大的数组,其中包含格式化为两列观察值的值。有时,两列之间的观察结果是相同的:
v1,v2
x、 y
a、 b
a、 a
x、 x

为了节省时间和精力,我想做一个if语句,如果两列相同,则只打印0,然后继续。如果值相同,则无需通过下游分析运行这些实例

这就是我到目前为止所做的,只是为了测试if语句。它还没有识别出任何列相等的实例

脚本:

mylines=[]

with open('xxxx','r') as myfile:
    for myline in myfile:
        mylines.append(myline)             ##reads the data into the two column format mentioned above

rang=len(open ('xxxxx,'r').readlines( ))   ##returns the number or lines in the file

for x in range(1, rang):
li = mylines[x] ##selected row as defined by x and the number of lines in the file spit = li.split(',',2) ##splits the selected values so they can be accessed seperately print(spit[0]) ##first value print(spit[1]) ##second value if spit[0] == spit[1]: print(0) else: print('Issue')

输出: 192Alhe52 192Alhe52

问题##应为0

188阿尔赫48 192Alhe52

发行

191阿尔赫51 192Alhe52

发行

如何让python重新证明某些观察值实际上是相等的


Tags: the实例innumberforifas语句
2条回答

读取值并将其存储在数组中时,也可以存储'\n',这是一个换行字符,因此数组实际上如下所示

print(mylist)
['x,y\n', 'a,b\n', 'a,a\n', 'x,x\n']

要解决此问题,必须使用strip(),这将删除此字符以及字符串末尾偶尔出现的空格,这些空格也会影响比较

mylines.append(myline.strip())

您不应该使用rang=len(open ('xxxxx,'r').readlines( )),因为您正在再次读取该文件

rang=len(mylines)

有一种更具可读性的pythonic方法来复制你的for

for li in mylines[1:]:
    spit = li.split(',')
    if spit[0] == spit[1]:
        print(0)
    else:
        print('Issue')

甚至

for spit.split(',') in mylines[1:]:
    if spit[0] == spit[1]:
        print(0)
    else:
        print('Issue')

将从第一个元素开始在数组mylines上迭代。
另外,如果您对python软件包感兴趣,您应该看看pandas。假设您有一个csv文件:

import pandas as pd
df = pd.read_csv('xxxx')
for i, elements in df.iterrows():
    if elements['v1'] == elements['v2']:
        print('Equal')
    else:
        print('Different')

我会成功的。如果需要修改值并写入另一个文件

df.to_csv('nameYouWant')

首先,equals测试的问题可能是因为在这样的行上迭代也会产生换行符。有一个字符串函数可以去掉它,.strip()。另外,split的参数是2,它将行拆分为三个组,但这里可能没有显示。使用csv模块时,您可以避免自己解析它,因为您的文件可能是:

import csv

with open("yourfile.txt") as file:
    reader = csv.reader(file)
    next(reader)  # skip header
    for first, second in reader:
        print(first)
        print(second)
        if first == second:
            print(0)
        else:
            print("Issue")

相关问题 更多 >