Convert numbers string in list to number int - python-3.x

In Python, I want to convert all strings in a list to integers.
So if I have:
list1 = ['10,20,30']
How do I make it:
list1 = [10,20,30]

try this:
list1 = [int(i) for i in list1[0].split(',')]

First of all you have to define what the array contains, for how you have wrote the questions the array is:
0: 10,20,30
if your array is made of strings like that then you should make a regex to identify the numbers in every string and then convert the number into an integer.
But I think that your array is actually:
0: 10
1: 20
2: 30
In this case you would want to do:
for every number in the array
make the number an integer
which would be
for num in list:
# if the value is a string
if type(num) == str: # just to be sure
num = int(num)
In python every data type is easily changeable through int, float or str, but remember to assign the number after you have converted it.
int(num) would make a number an integer but would not actually convert it because have not stored it, you should do num = int(num) because those are functions that return what to want, to really understand how they works mean you should search about dynamically typed languages and functions

Related

What can I do to add a list and sort out all the prime numbers in the list? Python 3

I am creating a program that
accepts an inputted list
finds all the prime numbers and only displays them.
I tried many different methods, many derived from existing prime filters, but they have hardcoded lists rather user-inputted ones.
I just can't seem to get a filter working with inputting a list, then filtering the prime numbers.
my_list = input("Please type a list")
list(my_list)
prime=[]
for i in my_list:
c=0
for j in range(1,i):
if i%j==0:
c+=1
if c==1:
prime.append(i)
return (prime)
When you get input, you're getting a string. You can't cast a string to a list immediately. Maybe you can request the user to use a separator between the numbers then use split method and cast strings to integers like this:
my_list = input("Please enter the list of numbers and use space seperator")
s_list = my_list.split()
cast_list = [int(num) for num in s_list]
Then, you can work on your prime number task based on your preferred algorithm.
Not sure what your c variable is for, current_number? Your loop returns 'str' object cannot be interpreted as an integer for me. I have used len(my_list) to get the length for the loop.
range() defines as range(start, stop, step) - learn more - it accepts integers and parameters are partially optional.
I copied the code from https://www.codegrepper.com/code-examples/python/how+to+find+prime+numbers+in+list+python
my_list = input("Please type a list")
primes = []
for i in range(0, len(my_list)):
for j in range(2, int(i ** 0.5) + 1):
if i%j == 0:
break
else:
primes.append(i)
print(primes)
More helpful resources from SO: Python function for prime number
I hope this helps.

How to convert percentage to decimal when it is in list

rstocks = ['5.57%','3.95%','5.26%','5.49%','-1,80%']
stocks =[]
for i in rstocks:
stock = rstocks[i]//100
stocks.append(stock)
It keeps showing
TypeError: list indices must be integers or slices, not str
There have two several errors in your code.
You may be mistakenly put the value -1,80% instead of -1.80%.
All the elements of your list are strings and strings have no integer
division
To get integer division of your element of the list, first, you need to convert the element into integer then use operator. Look at my code below. I convert all the elements into float then multiplied it to 100.
rstocks = ['5.57%', '3.95%', '5.26%', '5.49%', '-1.80%']
stocks = []
for x in rstocks:
stocks.append(float(x.strip('%'))*100)
print(stocks)
Output
[557.0, 395.0, 526.0, 549.0, -180.0]
Further you need to get integer value then you can typecast float to int.
int(float(x.strip('%'))*100)
Or typecast later all the elements of stocks.
print([int(s) for s in stocks])
I'm assuming that the value at last index on 'rstocks' is '-1.80%' instead of '-1,80%'. You can get a substring of the values in the loop and change the data type to float.
rstocks = ['5.57%','3.95%','5.26%','5.49%','-1.80%']
stocks =[]
for i in rstocks:
stock = float(i[:-1])
stocks.append(stock)

This is a simple Python question for list

Im trying to take in user input to get a list of numbers and then use a for loop to grab the largest value. For what I have now I can use 8237483294 but It will list each integer as its own independent value and will have its own place in the list so it would be [8,2,3,7,4,8,3,2,9,4] Which was an A+ for what I wanted. But now I want to take it to another place and take multi digit values such as [23,44332,32523,243,22,]
my code is
users_number = input("list number")
numbers = users_number
max = numbers[0]
for number in numbers:
if number > max:
max = number
print(max)
Use string.split().
#Get user input
# (no need for the two variables you used in your example)
numbers = input("List numbers separated by spaces").split()
#Convert to list of ints
numbers = [int(num) for num in numbers]
#Solution 1: use max()
print("Max value:", max(numbers))
#Solution 2: Iterate through list
max_val = numbers[0]
for num in numbers:
if num > max_val:
max_val = num
print(max_val)
On an additional note, I presented 2 possible methods for finding the max value. max() is a built-in that finds the maximum value in the list. There is also the iterating method, which is what you do in your code.
Here is a more user-friendly approach that asks for the numbers one by one from the user. The advantage is that you don't have to rely on your users to enter the correct syntax for a list.
numbers = []
while True:
number = input("Enter a number from your list. When finished with list, enter 'done': ")
if number == "done":
break
else:
numbers.append(int(number))
max_num = max(numbers)
print(max_num)
Simple and elegant one liner:
max(map(int, input("Enter a list: ").split()))

For loop list not updating

This should be a simple problem however at the moment I cannot understand why. Below is a simple code that is suppose to stripe of all strings and convert to int. However the results do not agree with what I wrote.
num = ('"28"', '"23"', '"35"', '"50"', 29488)
for i in num:
if type(i) is str:
i = i[1:-1]
print(i)
print(num)
Expected output
28
23
35
50
(28, 23, 35, 50, 29488)
Actual output
28
23
35
50
('"28"', '"23"', '"35"', '"50"', 29488)
Just found out I had a tuple, when I thought it was a list...
There are a few problems to address
Strings are immutable, so you're not really changing anything in the list, you're just reassigning the loop variable
You're not converting anything to ints, only removing characters from strings
If you want to be able to reassign elements within the nums, you need to use an actual list variable
For example
num = ['"28"', '"23"', '"35"', '"50"', 29488]
for i, n in enumerate(num):
if isinstance(n, str):
num[i] = int(n.strip('"'))
print(n)
print(num)
Re-assignment is missing to index position
Tuples are immutable, can not be set values using index position.
You can refer answer given by #cricket_007, also if you want single liner list compression way then refer below -
num = tuple(int(n.strip('"')) if isinstance(n, str) else n for n in num)
Then you will get again new tuple with values converted into int.

How can I make my program recognize if item is a string or an intiger?

I'm doing some python challenges for fun and I've found a challenge which tells me to make a program that takes an input and prints the numbers in the message.
but when I run the program it prints nothing but [] in the same number as the letters in the message, and also it do not recognize if a letter is actually a number or not, it just see every letter as a string and prints empty squares.
Here's the code:
WORDS = []
NUMBERS = []
Sentence = input()
for item in Sentence:
if item == str():
WORDS.append(item)
if item == int():
NUMBERS.append(item)
print(('[%s]' % ', '.join(map(str, NUMBERS))))
Have any ideas?
Here is probably what you meant. You have to split the sentence first.
All of the resulting items will be of type string, therefore isinstance will not help.
str.isdigit() checks if a string contains only digits. If it is a number, you can convert it to an integer using int.
WORDS = []
NUMBERS = []
Sentence = input()
for item in Sentence.split():
if item.isdigit():
NUMBERS.append(int(item))
else:
WORDS.append(item)
print(('[%s]' % ', '.join(map(str, NUMBERS))))
If you do not do the split first, it will work too, but give you just single characters in the WORDS list and single numbers in the NUMBERS list.
Typechecking is usually done using isinstance(obj, cls) :
x = 42
print(isinstance(x, int))
print(isinstance(x, str))
but in your case this will not work since input() always returns a string (a string composed of numeric characters is still a string), so the proper solution is to check if the string is composed only of numeric characters (and eventually build an int from it if you need proper ints).
Also, input() returns a single string, and from your namings (WORDS) I assume you want to iterate on the distinct words, not on each characters like you actually do:
words = []
numbers = []
sentence = input()
for item in sentence.strip().split():
if item.isnumeric():
numbers.append(int(item))
else:
words.append(item)
print(('[%s]' % ', '.join(map(str, numbers))))
Use the built-in isinstance function:
if isinstance(item, str):
WORDS.append(item)
if isinstance(item, int):
NUMBERS.append(item)

Resources