简体   繁体   中英

Remove spaces from a list of integers

I wrote a code that accepts multiple numbers and converts them into a list of integers. But I get them with spaces.

For example: I enter as input: 1,2,3,4,5 ( with commas ).

I get a list of [1, 2, 3, 4, 5]

Now I just need to delete the spaces but It's not working, I need it to look something like this [1,2,3,4,5] . I tried doing it this way:

numbers = input().split(',')

for i in range(0, len(numbers)):
    numbers[i] = int(numbers[i])
mylist = str(numbers).replace(' ','')
print(mylist)

This causes the square parentheses to be considered as items.

How do I delete the spaces the right way?

I think you are conflating the list and the representation of the list. The list itself doesn't have spaces, or even commas, it just has the items (in your case, the numbers). The representation of the list is just that - a way to represent the data inside of it in a normal, standard way. That standard includes commas and spaces.

If you want a new thing that represents the list and its items in the way you are saying, you can do that by making a new string just like that.

str(numbers).replace(' ','')

This has two functions in it, chained together. First, we do str(numbers) to get a string that is the string-representation of the list. This will be the string '[1, 2, 3, 4, 5]' . Then you replace any blank space-bar ' ' with nothing '' .

Edit:

I think I read your question too quickly and see that you did the exact same as what I have in my code here and said it isn't doing exactly what you want to do. I think the answer here is: no.

As I say in my first paragraph, there is the list and there is the lists representation. The function for the list's representation is a python built-in that can not be trivially overridden. I'm not saying it can't be done, but I don't think you'll get it done without defining some new things.

My understanding of your problem is that you want to input a list as a string and want to transform it into a Python list of numbers.

If you input the following string [1, 2, 3, 4, 5] , then you can split on , . Then you need to consider removing the leftmost and rightmost character, that correspond to the brackets:

numbers = input()[1:-1].split(', ')

for i in range(len(numbers)):
    numbers[i] = int(numbers[i])

print(numbers)

Other options to transform the numbers from strings to integers are the following:

  • Python built-in map function:

     numbers = input()[1:-1].split(', ') numbers = list(map(int, numbers)) print(numbers)
  • Python list comprehension:

     numbers = input()[1:-1].split(', ') numbers = [int(n) for n in numbers] print(numbers)

You can change the print behavior of the list to something you code yourself.

numbers = input().split(',')

for i in range(0, len(numbers)):
    numbers[i] = int(numbers[i])
mylist = str(numbers).replace(' ','')

print('[' + ','.join([str(n) for n in numbers]) + ']')

This prints a bracket [ , then each number separated by commas without any spaces, and finally the ending bracket ] .

Output looks like this:

1, 2, 3, 4, 5
[1,2,3,4,5]

What you might want to do is create a subclass of list that has the repr implementation you want. That way you can still operate on your list object as you would any other list (eg you can access numbers[0] and it will return the first number), but printing the list as a whole will produce the output you're looking for.

class MyList(list):
    def __repr__(self) -> str:
        return "[" + ",".join(repr(i) for i in self) + "]"

numbers = MyList(int(n) for n in input().split(","))
print(numbers)
print(numbers[0])

Input:

1,2,3,4,5

Output:

[1,2,3,4,5]
1

Since MyList is a list subclass, you can construct one from any iterable, including a generator expression (as in the code above) or an existing list, eg:

>>> n_copy = MyList(numbers)
>>> n_copy
[1,2,3,4,5]

You could use the re module's split function to deal with the whitespaces when splitting. Then you just need to join the elements with ',' and embed the whole thing between brackets in the string representation.

import re

numbers = re.split(r'\s*,\s*', input())

print(f"[{','.join(numbers)}]")

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