convert a list of strings to a list of numbers? - python

I would like to convert a list of following strings into integers:
>>> tokens
['2', '6']
>>> int(tokens)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string or a number, not 'list'
Other than writing a for loop to convert each member of the list tokens, is there a better way to do that? Thanks!

Just use list comprehension:
[int(t) for t in tokens]
Alternatively map the int over the list
map(int, tokens)
However map is changed in python3, so it creates an instance of the map and you would have to cast that back into a list if you want the list.

i = iter(list)
while i.next != None:
print int(i.next())

Related

Why am I getting TypeError 'list' object is not callable when using map function?

I am trying to separate some comma-separated numbers given as input:
numbers_ = input("Please enter numbers: ")
iterator_ = map(str.split(','), numbers_)
print (next(iterator_))
But I keep getting this error:
Please enter numbers: 1,2,3,4
Traceback (most recent call last):
File "C:\Users\tomerk\PycharmProjects\pythonProject\main.py", line 3, in <module>
print (next(iterator_))
TypeError: 'list' object is not callable
What am I doing wrong? String is an iterable object. I enter characters separated by commas without spaces.
You need to pass reference to function in map(). For your use case, you can use a lambda expression as:
numbers = '1,2,3,4'
iterator_ = map(lambda x: x.split(','), numbers)
print(next(iterator_))
# print: ['1']
Another example with external function:
def get_number(s):
return s.split(',')
iterator_ = map(get_number, numbers)
However if you want to get numbers from the string, then you do not need map here. You need to directly use str.split() as:
>>> numbers = '1,2,3,4'
>>> numbers.split(',')
['1', '2', '3', '4']
Additionally if you want to type-cast each number from str to int type, then you can use map as:
>>> list(map(int, numbers.split(',')))
[1, 2, 3, 4]
As the syntax is map(fun,itr). The Type Error rises in your code is for str.split(','), not for string. As str.split() returns a list which can't be used as function in map().
Instead of str.split(), you can use lambda function but carefully.
You can use this code :-
numbers = input("Please enter numbers: ")
#Tt creates a list of comma seperated elements of type str
temp=numbers.split(',')
iterator_ = map(int, temp)
print(next(iterator_))

How to print multiple non-consecutive values from a list with Python 3.5.1

I have created a list and want to choose a handful of items to print from the list. Below, I'd just like to print out "bear" at index 0 and "kangaroo" at index 3. My syntax is not correct:
>>> animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
>>> print (animals[0,3])
Traceback (most recent call last): File "", line 1, in
print (animals[0,3]) TypeError: list indices must be integers
or slices, not tuple
I tried with a space between the indexes but it still gives an error:
>>> print (animals[0, 3])
Traceback (most recent call last): File "", line 1, in
print (animals[0, 3]) TypeError: list indices must be
integers or slices, not tuple
I am able to print a single value or a range from 0-3, for example, with:
>>> print (animals [1:4])
['python', 'peacock', 'kangaroo']
How can I print multiple non-consecutive list elements?
To pick arbitrary items from a list you can use operator.itemgetter:
>>> from operator import itemgetter
>>> print(*itemgetter(0, 3)(animals))
bear kangaroo
>>> print(*itemgetter(0, 5, 3)(animals))
bear platypus kangaroo
Slicing with a tuple as in animals[0,3] is not supported for Python's list type. If you want certain arbitrary values, you will have to index them separately.
print(animals[0], animals[3])
list(animals[x] for x in (0,3)) is the subset you want. Unlike numpy arrays, native Python lists do not accept lists as indices.
You need to wrap the generator expression in list to print it because it does not have an acceptable __str__ or __repr__ on its own. You could also use str.join for an acceptable effect: ', '.join(animals[x] for x in (0,3)).
Python's list type does not support that by default. Return a slice object representing the set of indices specified by range(start, stop, step).
class slice(start, stop[, step])
>>>animals[0:5:2]
['bear', 'peacock', 'whale']
Either creating a subclass to implement by yourself or getting specified values indirectly. e.g.:
>>>map(animals.__getitem__, [0,3])
['bear', 'kangaroo']
print(animals[0] + " " + animals[3] + " " + ...)

Python - List Index Out Of Range In For Loop

I'm fairly new to python and I'm currently working on a program that will encrypt and decrypt strings. As part of it, I need the individual letters of the string to each be added to an empty list; for example, the string 'hello' would be entered into a list list like so:
['h','e','l','l','o']
The part of the code that is giving me this error can be found below. Thanks.
emptyList=[]
message=input("What Would You Like To Encrypt?\n")
messageLength=len(message)
for count in range(0,messageLength):
emptyList=[]
emptyList[count].append(message[count])
You are trying to address indices in an empty list:
>>> lst = []
>>> lst[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> lst[0] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
If you wanted to add elements to a list, just use list.append() directly on the list object itself to create more indices; don't create new empty lists each time:
emptyList=[]
messageLength=len(message)
for count in range(0,messageLength):
emptyList.append(message[count])
Not that you need to be this elaborate, the following is enough:
emptyList = list(message)
list() takes any iterable and adds all the elements of that iterable to a list. Since a string is iterable, producing all the characters in that string, calling list() on a string creates a list of those characters:
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Basically you want just read from the input and then output a list
Python 2.7
message=raw_input("What Would You Like To Encrypt?\n")
print list(message)
Python 3.X
message=input("What Would You Like To Encrypt?\n")
print(list(message))
Output
If you input Hello
['H', 'e', 'l', 'l', 'o']

"Can only iterable" Python error

Hello my fellow programmers.
I am a fairly new programmer, and now I am facing a great predicament. I am getting the error:
can only assign an iterable
Firstly I don't know what that means.
Secondly I will leave my code for you professionals to critique it:
def num_top(int_lis):
duplic_int_lis = int_lis
int_firs= duplic_int_lis [0]
int_lis[:] = duplic_int_lis [int_firs]
Basically I am trying to find the [0] element in the list and then using that int as an index position to find the integer at that index position.
int_lis[:] = duplic_int_lis [int_firs] means assign all the items of duplic_int_lis [int_firs] to int_lis, so it expects you to pass an iterable/iterator on the RHS.
But in your case you're passing it an non-iterable, which is incorrect:
>>> lis = range(10)
>>> lis[:] = range(5)
>>> lis #all items of `lis` replaced with range(5)
[0, 1, 2, 3, 4]
>>> lis[:] = 5 #Non-iterable will raise an error.
Traceback (most recent call last):
File "<ipython-input-77-0704f8a4410d>", line 1, in <module>
lis[:] = 5
TypeError: can only assign an iterable
>>> lis[:] = 'foobar' #works for any iterable/iterator
>>> lis
['f', 'o', 'o', 'b', 'a', 'r']
As you cannot iterate over an integer, hence the error.
>>> for x in 1: pass
Traceback (most recent call last):
File "<ipython-input-84-416802313c58>", line 1, in <module>
for x in 1:pass
TypeError: 'int' object is not iterable
The RHS of a slice-assignment must be an iterable, not a scalar. Consider slice-deleting and then appending instead.
An iterable is a thing with multiple items that you can iterate through (for example: take the 1st value do something, then the 2nd do something, etc...) Lists, dictionaries, tuples, strings have several items in them and can be used as iterables. As a counterexample: number types don't qualify as iterable.
Remember that computers count from #0 so: if you want the first value of a list you can use
my_list[0]
before you go further I would suggest watching this video about looping. https://www.youtube.com/watch?v=EnSu9hHGq5o

Python: Create associative array in a loop

I want to create an associative array with values read from a file. My code looks something like this, but its giving me an error saying i can't the indicies must be ints.
Thanks =]
for line in open(file):
x=prog.match(line)
myarray[x.group(1)]=[x.group(2)]
myarray = {} # Declares myarray as a dict
for line in open(file, 'r'):
x = prog.match(line)
myarray[x.group(1)] = [x.group(2)] # Adds a key-value pair to the dict
Associative arrays in Python are called mappings. The most common type is the dictionary.
Because array indices should be an integer
>>> a = [1,2,3]
>>> a['r'] = 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>> a[1] = 4
>>> a
[1, 4, 3]
x.group(1) should be an integer or
if you are using map define the map first
myarray = {}
for line in open(file):
x=prog.match(line)
myarray[x.group(1)]=[x.group(2)]

Categories

Resources