簡體   English   中英

我是編碼新手,在 csv 文件中找到最大值浮點數后,我想打印整行,其中包括字符串。 我正在使用蟒蛇

[英]I'm new to coding, after finding the maximum value float in the csv file, I want to print the whole row, which includes strings. I'm using python

import csv
with open('Prenoms.csv', 'r') as f:              # open file variable f
   reader = csv.reader(f)                       # read file
   next(reader)                                   # skip the first line
   answer = max(float(column[3].replace(',', '')) for column in reader)
print(answer)                                     # show max value                                  
#print("hi")                                      # Debugging line of code (works)
float_value = answer
string_value = str(float_value)                  # translate from float to string
f = open("Prenoms.csv","r")                       # Open file for read only

c = csv.reader(f, delimiter=',')                    # Read the file using the
                                                    # assigned delimiter
 while row in c: 
     if answer == row[3]:
        print(row)
     else:
         print("hi i'm here!")                    # while loop checks unlit list ends                    
for row in c:                                      # for loop checks for 11629 times
    if answer == row[3]:                            # if conditional to check if the 
                                                #row contains the desired float (max)
         print(row)                                 # Doesn't print but no errors are shown
        print("Hello World")                        # This is a debugging line of
                                                    # code but it doesn't print
f.close()
#print(row)                                         # This prints wrong row
#print("Hello World")                               # Debugging line of code (works)

這比你想象的要簡單得多:

with open('Prenoms.csv', 'r') as f:
    prenoms = csv.reader(f)
    next(prenoms)
    currentmax = 0.0
    therow = ''
    for row in prenoms:
        newval = float(row[3])
        if newval > currentmax:
            currentmax = newval
            therow = row
print(f'row {therow} contains the max val {maxval}')

我無法測試它,因為我沒有你的文件。 可能會出現問題,因為一旦您假設 ',' 不是分隔符(您在內容中替換它!),但稍后您重新打開同一個文件並將分隔符設置為 ','

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM