You may want to use the ndarray.item method, as in a.item(). This is also equivalent to (the now deprecated) np.asscalar(a). This has the benefit of working in situations with views and superfluous axes, while the above solutions will currently break. For example,
>>> a = np.asarray(1).view()
>>> a.item() # correct
1
>>> a[0] # breaks
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: too many indices for array
>>> a = np.asarray([[2]])
>>> a.item() # correct
2
>>> a[0] # bad result
array([2])
This also has the benefit of throwing an exception if the array is not actually a scalar, while the a[0] approach will silently proceed (which may lead to bugs sneaking through undetected).
>>> a = np.asarray([1, 2])
>>> a[0] # silently proceeds
1
>>> a.item() # detects incorrect size
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: can only convert an array of size 1 to a Python scalar
Answer from Aaron Voelker on Stack OverflowYou may want to use the ndarray.item method, as in a.item(). This is also equivalent to (the now deprecated) np.asscalar(a). This has the benefit of working in situations with views and superfluous axes, while the above solutions will currently break. For example,
>>> a = np.asarray(1).view()
>>> a.item() # correct
1
>>> a[0] # breaks
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: too many indices for array
>>> a = np.asarray([[2]])
>>> a.item() # correct
2
>>> a[0] # bad result
array([2])
This also has the benefit of throwing an exception if the array is not actually a scalar, while the a[0] approach will silently proceed (which may lead to bugs sneaking through undetected).
>>> a = np.asarray([1, 2])
>>> a[0] # silently proceeds
1
>>> a.item() # detects incorrect size
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: can only convert an array of size 1 to a Python scalar
Just access the first item of the list/array, using the index access and the index 0:
>>> list_ = [4]
>>> list_[0]
4
>>> array_ = np.array([4])
>>> array_[0]
4
This will be an int since that was what you inserted in the first place. If you need it to be a float for some reason, you can call float() on it then:
>>> float(list_[0])
4.0
python - How do I convert all of the items in a list to floats? - Stack Overflow
No way i am trying lets me convert string list into float list
python - How to convert one element lists to float - Stack Overflow
string - in Python how to convert number to float in a mixed list - Stack Overflow
[float(i) for i in lst]
to be precise, it creates a new list with float values. Unlike the map approach it will work in py3k.
map(float, mylist) should do it.
(In Python 3, map ceases to return a list object, so if you want a new list and not just something to iterate over, you either need list(map(float, mylist) - or use SilentGhost's answer which arguably is more pythonic.)
Not able to convert the "close_list" list into a float? list? I've tried a lot of ways that I see on the internet a lot that it's too much to put in here, and i am still getting an error of:" Exception has occurred: TypeError:list indices must be integers or slices, not float File "{filename}\import csv.py", line 25, in <module> diff = close_list[i] - price_compare TypeError: list indices must be integers or slices, not float ".
Am i missing anything that needs to be declared or imported, updated extensions? I am doing exactly what the internet says and even putting in "import numpy as np" and that's not working and am getting real disappointed. i have tried updating it and numpy is already up to date. How can i modify this so i can actually subtract price_compare from close_list[i].
import csv
import os
import sys
import numpy as np
close_list = ['0.0', '1.0', '2.5', '2.0']
len = len(close_list)
price_compare = [close_list[0]]
diff = 0.0
price=0
# [float(i) for i in value]
diff_close_list = []
for i in range(1,len):
i = float(i)
# price_compare = float(price_compare)
diff = close_list[i] - price_compare
price_compare = i
print(type(i))
print(i)
print(type(price_compare))
print(price_compare)
print(type(diff))
print(diff)
diff_close_list.append(diff)
# print(diff_close_list)
Because using the .findall() function of re returns a list with the matches. When none is found, then the return is an empty list, when there's something, it returns a list with all the results, if you are iterating over values in a list then you will get one of two:
- Empty lists when the regex is not present.
- 1-value list when the regex is present.
The simplest way to deal with is to add [0] to the result of the .findall() function.
From the documentation:
Return all non-overlapping matches of pattern in string, as a list of string.
Try this:
[press.append(float(p1)) for p1 in pressure]
>>> a = ['str','5','','4.1']
>>> a2 = []
>>> for s in a:
... try:
... a2.append(float(s))
... except ValueError:
... a2.append(s)
>>> a2
['str', 5.0, '', 4.0999999999999996]
If you're doing decimal math, you may want to look at the decimal module:
>>> import decimal
>>> for s in a:
... try:
... a2.append(decimal.Decimal(s))
... except decimal.InvalidOperation:
... a2.append(s)
>>> a2
['str', Decimal('5'), '', Decimal('4.1')]
for i, x in enumerate(a):
try:
a[i] = float(x)
except ValueError:
pass
This assumes you want to change a in place, for creating a new list you can use the following:
new_a = []
for x in a:
try:
new_a.append(float(x))
except ValueError:
new_a.append(x)
This try/except approach is standard EAFP and will be more efficient and less error prone than checking to see if each string is a valid float.
You can use sum() with a generator expression to convert each number in the list to float utilizing str.join:
nums = [
['2', '.', '7'],
['۳'],
['۳', '۰', '۶'],
['۷', '۴'],
['۵'],
['۹', '۰'],
['۱', '۰'],
['۱', '۵'],
['۲', '۶'],
]
for num in nums:
print(f'{num} =', float(''.join(num)))
total = sum(float(''.join(num)) for num in nums)
print(f'{total = }')
Output:
['2', '.', '7'] = 2.7
['۳'] = 3.0
['۳', '۰', '۶'] = 306.0
['۷', '۴'] = 74.0
['۵'] = 5.0
['۹', '۰'] = 90.0
['۱', '۰'] = 10.0
['۱', '۵'] = 15.0
['۲', '۶'] = 26.0
total = 531.7
Based on what you've provided, you're looking to:
- Accumulate numbers (Persian and Arabic) from a .docx into a list
- Sum that list and return a float
In addition to the solutions already suggested, this is another way to do it:
from docx import Document
import re
document = Document("File.docx")
text = " ".join(paragraph.text for paragraph in document.paragraphs)
# Find numbers, converting the Persian numbers to Arabic
persian_to_arabic = str.maketrans("۰۱۲۳۴۵۶۷۸۹", "0123456789")
numbers = re.findall(pattern=r"-?\d+\.\d+|-?\d+|[۰۱۲۳۴۵۶۷۹]+", string=text)
converted_numbers = [num.translate(persian_to_arabic) for num in numbers]
# Sum the list and return a float
total = sum(map(float, converted_numbers))
print(total)
Testing with the following input:
document = Document()
document.add_paragraph("The total cost is $45.67 and the discount is $5.50.")
document.add_paragraph("The Persian digits for 123 are ۱۲۳.")
document.add_paragraph("A negative number like -123.45 should be considered.")
This gives us ['45.67', '5.50', '123', '123', '-123.45'], which sums to 173.72000000000003.