I have a list in python and I'm searching the first occurrence of a value (>=5000000), but it returns the first of >=500000.
Here the command:
First_Range_Init_Freq = next(x for x in Freq_Cust if x > '5000000.000')
The strange is, it works fine if I search an exact value in the list with "==", but returns wrong value if I search something bigger or equal ">=".
Any ideas?
Not sure if I understand problem correctly (insufficient data).
Are you trying to,
1) Get first occurrence of value >=5000000 in a list?
2) Or its position?
3) You are comparing a int (>=5000000) with a stringx >
'5000000.000'
Anyway, If its first occurrence you are trying to find you can use array index method as below. (problem using a sample list)
Freq_Cust = ['4800000.000', '5000000.000' , '5000001.000', '50000010.000', '4900000.000', '500000.000' ]
First_Range_Init_Freq = [Freq_Cust.index(x) for x in Freq_Cust if x >= '5000000.000'][0]
print Freq_Cust[First_Range_Init_Freq]
Result:
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
5000000.000
>>>
For its position you can get using,
>>> print First_Range_Init_Freq
1
I am assuming you are comparing string with string or int with int. Else you will need to balance the comparision with correct type.
Let me know if this is not what you are looking for. And update question with more details.
EDIT1
Based on your comments. I believe the problem is that you are comparing a number as text and hence its giving incorrect result.
For e.g. see below,
>>> '5000000' == '5000000.000'
False
>>> '5000000.000' > '5000000'
True
>>> 5000000 == 5000000.000
True
>>>
A textual '5000000' is not = '5000000.000' , while a int 5000000 number is = float 5000000.000.
So, if you map your list values to float and also the comparision is done with a float , it will yield correct result.
Freq_Cust = ['4800000', '5000000' , '5000001', '50000010', '49000000', '500000' ]
Freq_Cust = map(float,Freq_Cust)
First_Range_Init_Freq = [Freq_Cust.index(x) for x in Freq_Cust if x >= float('5000000.000')][0]
print Freq_Cust[First_Range_Init_Freq]
>>>
5000000.0
>>>
Ofcourse you can just compare using x >= 5000000.000 or x >= 5000000.
If your list values are part int and part float, you may want to map to float as a catch-all solution.
Related
I am comparing the following dates as:
result = 2018-06-29T20:56:41+00:00 <= 2018-06-30T00:38:32Z
But this is giving as false. How can I make the 2 dates compare to True as Cleary 29 < 30. Initially, I thought it has to do with the timezone but on google search, found out that both formats are UTC timezone. Can anyone help me understand if that's correct and then compare these results to true?
Are you actually converting them to datatime objects, e.g.:
In []:
d1 = datetime.strptime("2018-06-29T20:56:41+00:00", "%Y-%m-%dT%H:%M:%S%z")
d2 = datetime.strptime("2018-06-30T00:38:32Z", "%Y-%m-%dT%H:%M:%S%z")
d1 <= d2
Out[]:
True
Note: in Py3.7 the first of these could be replaced with datetime.fromisoformat()
But even the string forms should also return True, so not sure why you are getting False:
In []:
"2018-06-29T20:56:41+00:00" <= "2018-06-30T00:38:32Z"
Out[]:
True
I need to figure out how to read in this data of the filename 'berlin52.tsp'
This is the format I'm using
NAME: berlin52
TYPE: TSP
COMMENT: 52 locations in Berlin (Groetschel)
DIMENSION : 52
EDGE_WEIGHT_TYPE : EUC_2D
NODE_COORD_SECTION
1 565.0 575.0
2 25.0 185.0
3 345.0 750.0
4 945.0 685.0
5 845.0 655.0
6 880.0 660.0
7 25.0 230.0
8 525.0 1000.0
9 580.0 1175.0
10 650.0 1130.0
And this is my current code
# Open input file
infile = open('berlin52.tsp', 'r')
# Read instance header
Name = infile.readline().strip().split()[1] # NAME
FileType = infile.readline().strip().split()[1] # TYPE
Comment = infile.readline().strip().split()[1] # COMMENT
Dimension = infile.readline().strip().split()[1] # DIMENSION
EdgeWeightType = infile.readline().strip().split()[1] # EDGE_WEIGHT_TYPE
infile.readline()
# Read node list
nodelist = []
N = int(intDimension)
for i in range(0, int(intDimension)):
x,y = infile.readline().strip().split()[1:]
nodelist.append([int(x), int(y)])
# Close input file
infile.close()
The code should read in the file, output out a list of tours with the values "1, 2, 3..." and more while the x and y values are stored to be calculated for distances. It can collect the headers, at least. The problem arises when creating a list of nodes.
This is the error I get though
ValueError: invalid literal for int() with base 10: '565.0'
What am I doing wrong here?
This is a file in TSPLIB format. To load it in python, take a look at the python package tsplib95, available through PyPi or on Github
Documentation is available on https://tsplib95.readthedocs.io/
You can convert the TSPLIB file to a networkx graph and retrieve the necessary information from there.
You are feeding the string "565.0" into nodelist.append([int(x), int(y)]).
It is telling you it doesn't like that because that string is not an integer. The .0 at the end makes it a float.
So if you change that to nodelist.append([float(x), float(y)]), as just one possible solution, then you'll see that your problem goes away.
Alternatively, you can try removing or separating the '.0' from your string input.
There are two problem with the code above.I have run the code and found the following problem in lines below:
Dimension = infile.readline().strip().split()[1]
This line should be like this
`Dimension = infile.readline().strip().split()[2]`
instead of 1 it will be 2 because for 1 Dimension = : and for 2 Dimension = 52.
Both are of string type.
Second problem is with line
N = int(intDimension)
It will be
N = int(Dimension)
And lastly in line
for i in range(0, int(intDimension)):
Just simply use
for i in range(0, N):
Now everything will be alright I think.
nodelist.append([int(x), int(y)])
int(x)
function int() cant convert x(string(565.0)) to int because of "."
add
x=x[:len(x)-2]
y=y[:len(y)-2]
to remove ".0"
My day for asking for help.
I have a big list of strings, created from a 13225 line text file:
with open(dest_file) as f2:
content_dest = [line.rstrip('\n') for line in f2]
My search string is mp.
Checking for mp in the list fails. All items in the list are
<type str>
When I iterate over the list, mp is found.
I don't see anything obvious (again) why this is so. I'm after a list index so I can mess with the data at index + something by accessing the indices I need in the big list. Since my iterations 'work', I guess my question is how do I get the 'mp in list' code to actually work..? And/or why doesn't mp in list' work?? Many thanks.
mp = 'r1_crvR_2_29040_-8580_180'
chk = mp in content_dest
print '**', chk
for x in content_dest:
chk = mp in x
if chk:
print 'Found:', mp, x
print type(mp), type(x)
for i in range(0, len(content_dest)):
chk = mp in content_dest[i]
if not chk:
pass
else:
print 'Found:', mp, content_dest[i], i
results in:
** False
Found: r1_crvR_2_29040_-8580_180 Name "r1_crvR_2_29040_-8580_180"
<type 'str'> <type 'str'>
Found: r1_crvR_2_29040_-8580_180 Name "r1_crvR_2_29040_-8580_180" 11846
mp in list
this works as: to check if string is in list.
As I can understand from the code above, you have only one line in the file with the requested substring. This line is:
Name "r1_crvR_2_29040_-8580_180"
for easier understanding I'll show you another example:
my_list = ["abc"]
check = 'a' in my_list
what should be the result of check?
False, sure, because we have no this string, a in our list.
To verify if there is some strings which consists of our string we can do:
double_check = any(['a' in x for x in my_list])
double_check will show us if there is some string in our list which consists of the requested string.
There is a difference searching in a list or in the items of a list.
For example,ais not in the list:
>>> L = ['abc', 'xyz']
>>> 'a' in L
False
but it is in one item of the list:
>>> for x in L:
... if 'a' in x:
... print 'found'
...
found
Here:
>>> 'a' in L
is equivalent to:
chk = mp in content_dest
and your loop to the loop above.
I have 4 lists such as:
m1_jan = [2.3,3.2]
m1_feb = [3.2,2.3]
m2_jan = [1.2,1.7]
m2_feb = [4.5,6.7]
and I want to get minimum value of each list and tried following:
mon = ['jan','feb']
for i in xrange(1,3,1):
for j in mon:
l = 'm' + str(i) + '_' + j
print l, min(l)
I get list names right but not getting correct minimum values and instead get following:
m1_jan 1
m1_feb 1
m2_jan 2
m2_feb 2
Any suggestions how to get minimum value of each list?
If we change:
print l, min(l)
to:
print globals()[l], min(globals()[l])
The output will be as requested:
[2.3, 3.2] 2.3
[3.2, 2.3] 2.3
[1.2, 1.7] 1.2
[4.5, 6.7] 4.5
Explanation:
The variables that you're looking for are stored in the dictionary of globals()
That said, it's a better practice to store these variables in your own dictionary and access them through it, instead of relying on globals()
You could just use a dictionary
d = {}
d['m1_jan'] = m1_jan
d['m1_feb'] = m1_feb
d['m2_feb'] = m2_feb
d['m2_jan'] = m2_jan
for mon, min_val in d.items():
print("{} {}".format(mon, min(min_val)))
Output
m1_feb 2.3
m2_feb 4.5
m2_jan 1.2
m1_jan 2.3
I have a dictionary like
>> dic = {'yearly': 79.00, 'monthly': 59.00}
when the dic is printed the, it removes the last zero from the decimal number.
>> print dic
>> {'monthly': 59.0, 'yearly': 79.0}
How to get the original value as 59.00 not as 59.0 ?
when you print a number, you could do
x = 5
print '%.2f' % x
where the 2 specifies u want 2 decimal place
alternatively, the more updated/versatile version is
print '{:.2f}'.format(x)
if you really want your dict object to print nicely, you could create a custom class that specifies the __str__ function to print the dict however you want to print it