I am trying to assign a certain list position value to a certain value in another list. The value in the second list is 24.199999999999996. However, when i assign that value to a certain index value in the first list I get the value 24.2, when I print it. How do I keep the value as it is?
The value is getting rounded when printed for display purposes by default. The actual value in the list does not change. If you actually check it:
value == 24.2
False will be returned.
If you do not want this printing behaviour you have to round your numbers to a reasonable precision. You can use the built-in function 'round'.
>>> round(1.33333333, 5)
1.33333
Related
I'm trying to sort a list of dollar amounts from lowest to highest using python's built in sort ability, but when I call on it, it sorts the numbers super screwy. It starts at $10,000 then goes up to $19,0000 (which is the highest) then jumps down to $2,000 and counts up from there ostensibly because 2 is bigger than 1. I don't know how to correct for this. The code I've used is below.
numbers=[['$10014.710000000001'], ['$10014.83'],['$11853.300000000001'],
['$19060.010000000006'],['$2159.1099999999997'],['$3411.1400000000003']]
print(sorted(numbers))
The key insight here is that the values in your list are actually strings, and strings are compared lexically: each character in the string is compared one at a time until the first non-matching character. So "aa" sorts before "ab", but that also means that "a1000" sorts before "a2". If you want to sort in a different way, you need to tell the sort method (or the sorted function) what it is you want to sort by.
In this case, you probably should use the decimal module. And you want the key attribute of the sort method. This will sort the existing list you have, only using the converted values during the sorting process.
import decimal
def extract_sortable_value(value):
# value is a list, so take the first element
first_value = value[0]
return decimal.Decimal(first_value.lstrip('$'))
numbers.sort(key=extract_sortable_value)
Equivalently, you could do:
print(sorted(numbers, key=extract_sortable_value))
Demo: https://repl.it/repls/MiserableDarkPatches
You are not sorting numbers but strings, which explains the "weird" result. Instead, change your type to float and sort the resulting list:
In [3]: sorted([[float(el[0][1:])] for el in numbers])
Out[3]:
[[2159.1099999999997],
[3411.1400000000003],
[10014.710000000001],
[10014.83],
[11853.300000000001],
[19060.010000000006]]
I need the el[0] because every number is inside its own list, which is not a good style, but I guess you have your reasons for this. The [1:] strips away the $ sign.
EDIT really good point made in the comments. More robust solution:
from decimal import Decimal
import decimal
decimal.getcontext().prec = 4
sorted([Decimal(el[0][1:]) for el in numbers])
Out[8]:
[Decimal('2159.1099999999997'),
Decimal('3411.1400000000003'),
Decimal('10014.710000000001'),
Decimal('10014.83'),
Decimal('11853.300000000001'),
Decimal('19060.010000000006')]
Your numbers are currency values. So as pointed out in the comments below, it might make sense to use Python's decimal module which offers several advantages over the float datatype. (See link for further information.)
If, however, this is only an exercise for better getting to know Python, as I suspect. You might look for a simpler solution:
The reason, why your sorting doesn't work, is because your numbers are stored in the list inside another list as a string. You have to convert them to integers or floats before sorting has the effect you're looking for:
numbers=[
['$10014.710000000001'],
['$10014.83'],
['$11853.300000000001'],
['$19060.010000000006'],
['$2159.1099999999997'],
['$3411.1400000000003']
]
numbers_float = [float(number[0][1:]) for number in numbers]
numbers_float.sort()
print(numbers_float)
Which prints:
[2159.1099999999997, 3411.1400000000003, 10014.710000000001, 10014.83, 11853.300000000001, 19060.010000000006]
When you look at float(number[0][1:]), then [0] takes the first (and only) number of your (inner) number list, [1:] strips the $ sign and finally float does the conversion to floating point number.
If you want the $ sign back:
for number in numbers_float:
print("${}".format(number))
Which prints:
$2159.1099999999997
$3411.1400000000003
$10014.710000000001
$10014.83
$11853.300000000001
$19060.010000000006
I want to know if any of the values contained in a 1024 length array are greater than the value 1.2. I've found the median value of the array and its 1.1, so I know the array contains values that are higher and lower than 1. The code that I'm using is shown below and the resulting message i'm getting is "No signal present".
if in1_norm.any()>=1.2: ## Comparison of array to threshold. Using
## a generic value for now
print "A signal is present"
else:
print "No signal is present"
I've read in a previous post that any() evaluates as a value of 1 or "true, so, I believe I'm not getting the correct result because the comparison is viewed as 1>=1.2, which is false. Is there any other way of doing this??
Thanks
The part in1_norm.any()>=1.2 will not do what you're intended. The any() function returns True if any of the array's items can be evaluated as True otherwise it will return False. You need to first compare your items with 1.2 then call the any on the results.
(in1_norm >= 1.2).any()
def calc_average(scores)
x = scores[1:]
return (sum(x) / float(len(x)))
Here is some code that is supposed to find the average of a list of numbers, but not count the lowest. I'm not sure how to find the lowest number in the list, remove it from it, and then find the average of that. Can anyone help? Thanks! (The lowest number isn't always the first number in the list, that's the mistake I made...)
You don't have to literally remove the item from the list; you can just remove it from the calculation.
def calc_average(scores)
return (sum(scores) - min(scores)) / float(len(x) - 1)
I would sort the list then romove the first element.
a = [ 3,2,6,3,8,7,2,1]
a.sort()
a = a[1:]
print a
print float(sum(a))/len(a)
The benefit of doing it this way, even though it is more work for just removing the single lowest value is that it is salable. Let's say you wanted to remove the lowest 2 or three values, that would be easy once you have the list sorted.
You can use the min() function to find the smallest value of a list, and then you can remove the value with the list.remove() function.
Check this out for reference https://docs.python.org/2/library/functions.html#min or https://docs.python.org/3.6/library/functions.html#min
You could use
return float((sum(scores) - min(scores))) / (len(scores) - 1)
That finds the sum of all the scores, then removes the smallest score, before dividing by the number of scores after the removal.
Note there is no error-checking here, so this will not work properly for a list of length zero or one. That float() is there to ensure floating point division in Python 2.x. This uses the full speed of Python functions, but it does loop over the scores twice. A hand-coded function would be faster in looping only once but would slow down again in executing multiple commands.
I am currently trying write a function to use the position of a min value on one list to reference a string on another list.
I have two list, one with states names and another with floats. I am using the min method to get the minimum value of the float list. The problem is, how I use an index to mark the position of that value then use it to return the state that holds the same position on the other list?
This is the code I am currently using, but it does not go all the way through the list before it returns a value, which is way too soon in the list.
def stateheart_min():
for item in heartdis_flt:
heartcount=0
heartcount+=1
min_index=0
if item == min(heartdis_flt):
min_index=heartcount
return states_fin[min_index:min_index+1]
This is a bit terse to read, but here is an alternative way to do it. You can use min to find the minimum value in values. Then you can use index to find the index at which the minimum occurs in the list. You can then use that returned index to index the correct element from states.
states = ['NY', 'PA', 'CA', 'MI']
values = [15.0, 17.5, 3.5, 25.4]
>>> states[values.index(min(values))]
'CA'
Try this:
index = min(zip(values, range(len(values))))[1]
This first builds a list of pairs, each having a value as first item and its index as second item. So when you find the minimum, the first item still has the main impact (the index will only be taken into account if the values are equal). Taking the index is then done using [1] in the end.
Not entirely sure what you are asking, but a dictionary might be a better choice. Also setting heartcount=0 inside the loop resets the variable back to 0 each iteration. Check your variables inside the loop.
I have an ordered dictionary like following:
source =([('a',[1,2,3,4,5,6,7,11,13,17]),('b',[1,2,3,12])])
I want to calculate the length of each key's value first, then calculate the sqrt of it, say it is L.
Insert L to the positions which can be divided without remainder and insert "1" after other number.
For example, source['a'] = [1,2,3,4,5,6,7,11,13,17] the length of it is 9.
Thus sqrt of len(source['a']) is 3.
Insert number 3 at the position which can be divided exactly by 3 (eg. position 3, position 6, position 9) if the position of the number can not be divided exactly by 3 then insert 1 after it.
To get a result like folloing:
result=([('a',["1,1","2,1","3,3","4,1","5,1","6,3","7,1","11,1","13,3","10,1"]),('b',["1,1","2,2","3,1","12,2"])]
I dont know how to change the item in the list to a string pair. BTW, this is not my homework assignment, I was trying to build a boolean retrival engine, the source data is too big, so I just created a simple sample here to explain what I want to achive :)
As this seems to be a homework, I will try to help you with the part you are facing problem with
I dont know how to change the item in the list to a string pair.
As the entire list needs to be updated, its better to recreate it rather than update it in place, though its possible as lists are mutable
Consider a list
lst = [1,2,3,4,5]
to convert it to a list of strings, you can use list comprehension
lst = [str(e) for e in lst]
You may also use built-in map as map(str,lst), but you need to remember than in Py3.X, map returns a map object, so it needs to be handled accordingly
Condition in a comprehension is best expressed as a conditional statement
<TRUE-STATEMENT> if <condition> else <FALSE-STATEMENT>
To get the index of any item in a list, your best bet is to use the built-in enumerate
If you need to create a formatted string expression from a sequence of items, its suggested to use the format string specifier
"{},{}".format(a,b)
The length of any sequence including a list can be calculated through the built-in len
You can use the operator ** with fractional power or use the math module and invoke the sqrt function to calculate the square-root
Now you just have to combine each of the above suggestion to solve your problem.