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

2024-09-30 08:37:15 发布

您现在位置: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语句替换循环列表,但这不起作用,我也不知道为什么。我也在if语句中转换为float,但是没有任何变化。你知道吗

我认为这很容易解决,但它不是(嗯,对我来说),所以我希望我得到一些帮助。提前谢谢。你知道吗


Tags: offorinputdataifline语句float
3条回答

一个简单的方法: 如果排序的列表与初始列表相同,则对列表进行排序;如果第一个值小于最后一个值,则对列表进行升序排序。不考虑列表中只有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内置的许多功能来替代。这是基于您提供的代码的解决方案。你知道吗

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

new_list = list()

for line in data:
    line = line.rstrip()
    first_empty = line.find(" ")
    items_whole = line[first_empty + 1:]
    items_list = items_whole.split()
    # Use a 'list comprehension' to convert the items list into a list of floats
    floats_list = [float(i) for i in items_list]

    # Use the built in 'sorted' method to sort the floats
    # If the sorted float list is the same as the original float list, then all the items are ascending
    if floats_list == sorted(floats_list):
        print items_list
        # Add the list of floats into the 'new_list' for any post processing
        new_list += [floats_list]

你离这儿不远,却在杂草丛中游荡。您需要通读build-in functions(这些在python版本中或多或少是相同的,我使用的是2.7)。你知道吗

这是我用过的解决方案,我相信更好的存在。我删除了示例中的键盘输入

new_list=list()

with open('data.txt') as Data2:
    for line in Data2:
        line2 = line.split()[1:]
        line2 = [float(v) for v in line2]
        if line2 == sorted(line2):
            new_list.append(line.rstrip())

print new_list
#['gsdg 1.2 2.2 5.7 8.2 10.2', 'adsdfhad 0.2 1.2 5.2 8.2 12.2']

这样做的两件事是引入with语句,在继续之后为您关闭文件。关闭文件是一种很好的做法。然后我用了和你一样的split()。然后列表理解将值从字符串转换为浮点值。这意味着您可以将这些值与排序后的值进行比较,如果它们与排序后的值相匹配的话。你知道吗

相关问题 更多 >

    热门问题