简体   繁体   English

如何将整数列表转换为字符串 - Python

[英]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编辑:文件中的数字应该是这样的:1 4 2 3... 在输出中是这样的: 1 2 3 4... 所以基本上用空格隔开

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.尽管您可以使用map来编写它,但生成器或列表推导式通常是首选样式。

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.由于list_a是整数列表,因此您可能会得到一个带有str1 += e的 TypeError 。

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...)它应该可以工作(未测试...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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