Python:仅提取值不断变大的文件中的行

标签 python

我正在尝试解决以下问题:我有一个这样构建的文件:

adsbhad 2.2 3.2 5.2 3.2 7.2
gsdg 1.2 2.2 5.7 8.2 10.2 
sdgghhad 1.2 0.2 3.2 2.2 5.2 
adsdfhad 0.2 1.2 5.2 8.2 12.2 
adrzertzd 1.2 13.2 2.2 10.2 9.2

我想编写一个脚本来检查行中的值是否只会变大,然后提取这些行。 在这种情况下,所需的行是第 2 行和第 4 行:

gsdg 1.2 2.2 5.7 8.2 10.2
adsdfhad 0.2 1.2 5.2 8.2 12.2

我尝试使用 for 循环和 if 语句,但它不起作用。似乎存在一些类型问题。到目前为止,这是我的代码(请客气,因为我是初学者!):

Data=raw_input("Please type name of input data! ")
Data2=open(Data)

new_list=list()

for line in Data2:
    line2=line.rstrip()
    first_empty=line2.find(" ")
    line3=line2[first_empty+1:]
    List_of_line=line3.split()
    express=0
    for i in List_of_line:
       flo_i=float(i)
       express=float(express)
       if express == 0 or flo_i > express:
          express=flo_i
          express=str(express)
          if express == List_of_line[4]:
             print List_of_line

我还尝试用 if 语句替换 list-for 循环,但这不起作用,我也不知道为什么。我还在 if 语句中转换为 float,但没有任何变化。

我认为这很容易解决,但事实并非如此(嗯,对我来说),所以我希望能得到一些帮助。提前致谢。

最佳答案

一个简单的方法: 如果排序后的列表与初始列表相同,则对列表进行排序;如果第一个值小于最后一个,则对列表进行升序排序。不考虑列表中只有 1 个值的情况。

...
for line in Data2:
    items = [float(n) for n in line.split()[1:]]
    sorted_items = sorted(items)
    if items == sorted_items and items[0] < items[-1]:
        print line

关于Python:仅提取值不断变大的文件中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29824217/

相关文章:

python - 在 Pyarrows 的 HdfsClient 中使用多处理

python - 比如说,send_message 和 send,在 @bot 事件中不起作用怎么办?不和谐.py

python - 无法在Python Flask中导入MySQLdb,未找到符号: _syslog$DARWIN_EXTSN

php - 如何使用 php 执行 shell cmd(python)并打印所有不断更新的输出?

python - 空分页对象 sqlalchemy

python - 错误 : (-215) ssize. width > 0 && ssize.height > 0 in function resize

python - 在 Python LXML 的 KML 文档中添加命名空间

python - 按键值pyspark分组

python - 如何停止 wxpython 中的线程?

python - python中不同组的缩放数值