从文件读取文本到数组的索引问题

时间:2019-08-03 16:31:11

标签: python

嗨,我尝试将文本文件读取为数组,但是当我读取2位数字时出现错误。

我想检查每个字符串中奇数或偶数的匹配情况。 我做错了什么?

到此文件1.txt:

1 2 3 4 3 6
4 5 8 6 4 2
15 4 22 5 8 21

i get:
   evenArray: [3, 5, 3]
   oddArray: [3, 1, 2]

with open('file1.txt') as file:
   array = file.readlines()




evenCounter = 0
oddCounter = 0

evenArray = []
oddArray = []

for x in array:
   for i in range(len(x) - 1):
       if(x[i] != " " and x[i + 1] != " " and x[i + 1] != '\n'):
           strTemp = x[i]
           strTemp += x[i+1]
           temp = int(strTemp)
       elif x[i] != " ":
           temp = int(x[i])

       if temp % 2 == 0:
            evenCounter += 1
        else:
            oddCounter += 1
evenArray.append(evenCounter)
oddArray.append(oddCounter)
evenCounter = 0
oddCounter = 0

2 个答案:

答案 0 :(得分:0)

尝试此代码。
每行是一个str。例如,第一行是'1 2 3 4 3 6'。这不是数字列表,必须将其拆分然后转换为ints

def is_even(x):
  if x == 1:
    return False

  for i in range(2, x//2 + 1):
    if x % i == 0:
      return False
  return True


with open('file1.txt', 'r') as file:
  lines = file.readlines()

  for line in lines:
    even_nos = []
    odd_nos = []

    numbers = map(int, line.split())
    for number in numbers:
      if is_even(number):
        even_nos.append(number)
      else:
        odd_nos.append(number)

    print(f'{len(even_nos)} even numbers: {even_nos}')
    print(f'{len(odd_nos)} odd numbers: {odd_nos}')
    print()

答案 1 :(得分:0)

像这样使用str.split()

with open('file1.txt') as file:
   array = file.readlines()




evenCounter = 0
oddCounter = 0

evenArray = []
oddArray = []

for x in array:
   for i in x.split():
       temp = int(i)
       if temp % 2 == 0:
            evenCounter += 1
       else:
            oddCounter += 1
evenArray.append(evenCounter)
oddArray.append(oddCounter)
evenCounter = 0
oddCounter = 0

print(evenArray)
print(oddArray)