Skip to content
Advertisement

Python create lists conditionally from txt file

I have a txt file with this structure of data:

3
100 name1
200 name2
50 name3
2
1000 name1
2000 name2
0

The input contains several sets. Each set starts with a row containing one natural number N, the number of bids, 1 ≤ N ≤ 100. Next, there are N rows containing the player’s price and his name separated by a space. The player’s prize is an integer and ranges from 1 to 2*109.

Expected out is:
Name2
Name2

How can I find the highest price and name for each set of data?

I had to try this:(find the highest price)

offer = []
name = []

with open("futbal_zoznam_hracov.txt", "r") as f:
    for line in f:
        maximum = []
        while not line.isdigit():
            price = line.strip().split()[0]
            offer.append(int(price))
            break
    maximum.append(max(offer[1:]))
print(offer)
print(maximum)
        

This creates a list of all sets but not one by one. Thank you for your advice.

Advertisement

Answer

You’ll want to manually loop over each set using the numbers, rather than a for loop over the whole file

For example

with open("futbal_zoznam_hracov.txt") as f:
    while True:
        try:  # until end of file 
            bids = int(next(f).strip())
            if bids == 0:
                continue  # or break if this is guaranteed to be end of the file 
            max_price = float("-inf")
            max_player = None
            for _ in range(bids):
                player = next(f).strip().split()
                price = int(player[0])
                if price > max_price:
                    max_price = price
                    max_player = player[1]
            print(max_player)
        except:
            break 
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement