質問

I have this code wrote in Python:

with open ('textfile.txt') as f:
     list=[]
     for line in f:
          line = line.split()
          if line: 
              line = [int(i) for i in line] 
              list.append(line)
     print(list)

This actually read integers from a text file and put them in a list.But it actually result as :

[[10,20,34]]

However,I would like it to display like:

10 20 34

How to do this? Thanks for your help!

役に立ちましたか?

解決

You probably just want to add the items to the list, rather than appending them:

with open('textfile.txt') as f:
    list = []
    for line in f:
        line = line.split()
        if line:
            list += [int(i) for i in line]

    print " ".join([str(i) for i in list])

If you append a list to a list, you create a sub list:

a = [1]
a.append([2,3])
print a    # [1, [2, 3]]

If you add it you get:

a = [1]
a += [2,3]
print a    # [1, 2, 3]!

他のヒント

with open('textfile.txt') as f:
    lines = [x.strip() for x in f.readlines()]

print(' '.join(lines))

With an input file 'textfiles.txt' that contains:

10
20
30

prints:

10 20 30

It sounds like you are trying to print a list of lists. The easiest way to do that is to iterate over it and print each list.

for line in list:
    print " ".join(str(i) for i in line)

Also, I think list is a keyword in Python, so try to avoid naming your stuff that.

If you know that the file is not extremely long, if you want the list of integers, you can do it at once (two lines where one is the with open(.... And if you want to print it your way, you can convert the element to strings and join the result via ' '.join(... -- like this:

#!python3
# Load the content of the text file as one list of integers.
with open('textfile.txt') as f:
    lst = [int(element) for element in f.read().split()]

# Print the formatted result.
print(' '.join(str(element) for element in lst))

Do not use the list identifier for your variables as it masks the name of the list type.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top