简体   繁体   中英

How do I convert a list of integers to a string - Python

So, I'm making a sorting algorithm, that takes a list of integers from a file & saves them to a new file. I've basically gotten it to work, but the only thing that's holding me back from finishing it is that it doesn't let me write the integer list to the new file. So... I try to convert the list to a string, but the code doesn't work correctly & I don't know what messes it up. Here's the code:

from pathlib import Path

content = Path('numbers.txt').read_text()
list_content = content.split()
integer_list = [int(x) for x in list_content]

def selection_sort(list_a):
    indexing_length = range(0, len(list_a)-1)


    for i in indexing_length:
        min_value = i

        for j in range(i+1, len(list_a)):
            if list_a[j] < list_a[min_value]:
               min_value = j

        if min_value != i:
            list_a[min_value], list_a[i] = list_a[i], list_a[min_value]


    str1 = ""  #here is where I think the problem is, but I don't know how to fix it.
    for e in list_a:
        str1 += e

    return str1


file = open('sorted_numbas.txt', 'w')
data = selection_sort(integer_list)
file.write(data)
file.close()

edit: The numbers in the file should look like this: 1 4 2 3... and in the output like this: 1 2 3 4... So basically separated by spaces

You can convert the integers to strings and then "join" them with spaces.

>>> data = [1, 2, 3, 4]
>>> " ".join(str(i) for i in data)
'1 2 3 4'

although you could write this using map , generators or list comprehensions are generally the preferred style.

Try to change

str1 = ""  #here is where I think the problem is, but I don't know how to fix it.
    for e in list_a:
        str1 += e

to

str1 = " ". join(map(str, list_a))

You are so close.

Where you suspect you have a problem -- you do.

  1. If you want to have space delimited integers again, you need to add them.
  2. Likely you get a TypeError with str1 += e since list_a is a list of ints.

This would fix it. Replace:

str1 = ""  #here is where I think the problem is, but I don't know how to fix it.
for e in list_a:
    str1 += e

With:

str1=' '.join(map(str, list_a))

And it should work (not tested...)

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