简体   繁体   中英

How to get a list of tuples from several text files (Part 2: Electric Boogaloo)?

Since my first question wasn't clear enough, I'm going to rewrite it so it's clearer (I'm sorry I wasn't clear in the 1st question).

I have a folder that has 46 subdirectories. Each subdirectory has a.txt file. The text within those.txt files varies in number of lines and looks like this:

0
0
0
1
...
1
0
0
1

I want to have a list with 46 tuples (1 for every subdirectory - and for each.txt file) and inside those tuples, I want to have the number of lines that have 0s and the number of lines that have 1s present in the text for the file that that tuple is assigned to. Something along the lines of this:

[(17342,2453),(342,127),...,(45003,69),(420,223)]

Currently my code (not working properly) is like this:

from pathlib import Path

def count_0s(paths):
  for p in paths:
    list_zeros = []
    list_ones = []
    for line in p.read_text().splitlines():
      zeros = 0
      zeros += line.count('0')
      ones = 0
      ones += line.count('1')
    list_zeros.append(zeros)
    list_ones.append(ones)    
  return list_zeros, list_ones

path = "/content/drive/MyDrive/data/classes/"
paths = Path(path).glob("*/marked*.txt")
n_zeros=count_0s(paths)
n_zeros

What changes do I need to apply so that, instead of 2 lists, I have a list with tuples?

Assuming you have two lists, the first with the number of zeros and the second with the number of ones, you can just rearrange the data at the end:

n_zeros = [1, 2, 3, 4]
n_ones = [5, 6, 7, 8]

pairs = []
for n_zero, n_one in zip(n_zeros, n_ones):
    pairs.append((n_zero, n_one))

print(pairs)

Should return

[(1, 5), (2, 6), (3, 7), (4, 8)]

A better way would be to do the pairing in your main loop, instead of saving two lists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM