Convert List into a integer or float - python-2.7

so i'm having a problem converting to a list to integer or float. what i mean in converting is like this. i have a list that has one element.
newList = ['2.0G']
i want that to convert into this
numFloat = 2.0
or
numInt = 2
i tried regex to extract the number from string so i can assign it to another variable
firstVariable = re.findall(r"[-+]?\d*\.\d+|\d+", newList[0])
i have to keep calling the index in firstVariable to access the 2.0 or 2

Does this work ?
newList = ['2.0G']
numFloat = ''.join([i for i in newList[0] if i.isdigit() or i == '.'])
print(numFloat)
The above code will print 2.0 to the console.
What I am doing here, is that I am going through each and every item in the first item of the list , and then checking if its a digit or a .. If its not any one of these I move to the next character.
Please note that I am doing newList[0] because you mentioned that your list has only one element.
Please let me know if this works for you.
Thanks.

Related

How to display interaction element with order way of list one in Kotlin

I have two lists and I want to return a result in the following way:
the result should contain elements that are in list one and list two
output should be same order as per first list
Input :
val first = listOf(1, 2, 3, 4, 5,7,9,15,11)
val second = listOf(2, 15 , 4,3, 11)
Output:
val output = listOf(2,3,4,15,11)
Please help me to learn how to get common values in both lists in order of list first in Kotlin.
You can do
val output = first.filter { second.contains(it) }
What you are looking for is the intersection of the two lists:
val output = first.intersect(second)
As pointed out by #Ivo the result is a Set which can be turned into a list with output.toList(). However, since the result is a set, it contains no duplicates, e.g. if first is listOf(1,2,3,1,2,3) and second is listOf(2,4,2,4), the result will be equal to setOf(2).
If this is not acceptable, the solution of #Ivo should be used instead.

List will not sort after appending variables to it (python 3)

I am working on another piece of code right now, however, I took a snippet out to show what happens when I try and sort a list after appending two variables to it. Any idea how I can fix this?
player1score = 10
player2score = 20
listwin = list()
listwin.append(player1score)
listwin.append(player2score)
sorted(listwin)
print(sorted(listwin))
Calling the sorted method does not update your list. You need to use list.sort():
player1score = 10
player2score = 20
listwin = list()
listwin.append(player1score)
listwin.append(player2score)
listwin.sort()
print(listwin)
The difference between those methods is that sorted(listwin) returns a copy of listwin without changing it, while listwin.sort() changes listwin.

Simulation in python for Unique matches of demand supply using lists

I have data in the form of list of lists where I am trying to match the demand and supply such that each demand matches uniquely to one supply item.
dmndId_w_freq = [['a',4,[1,2,3,4]],['b',6,[5,6,7,8,3,4]],['c',7,[6,5,7,9,8,3,4]],['d',8,[1,6,3,4,5,6,7,10]]]
num_sims = 1
for sim_count in range(num_sims):
dmndID_used_flag = {}
splID_used_flag = {}
dmndID_splId_one_match = {}
for i in dmndId_w_freq:
if i[0] not in dmndID_used_flag.keys():
for j in i[2]:
#print j
#print "CLICK TO CONTINUE..."
#raw_input()
if j in splID_used_flag.keys():
i[2].remove(j)
dmndID_splId_one_match[i[0]] = i[2][0]
splID_used_flag[i[2][0]] = 1
dmndID_used_flag[i[0]] = 1
print
print dmndID_splId_one_match
#print splID_used_flag
#print dmndID_used_flag
#raw_input()
I would expect the output dmndID_splId_one_match to be something like {'a':1,'b':5,'c':6,'d':3}.
But I end up getting {'a':1,'b':5,'c':6,'d':6}
So I am NOT getting a unique match as the supply item 6 is getting mapped to demands 'c' as well as demand 'd'.
I tried to debug the code by looping through it and it seems that the problem is in the for-loop
for j in i[2]:
The code is not going through all the elements of i[2]. It does not happen with the 'a' and 'b' part. but starts happening with the 'c' part. It goes over 6 and 5 but skips 7 (the third element of the list [6,5,7,9,8,3,4]). Similarly, in the 'd' part it skips the 2nd element 6 in the list [1,6,3,4,5,6,7,10]. And that is why the mapping is happening twice, since I am not able to remove it.
What am I doing wrong that it is not executing the for-loop as expected?
Is there a better way to write this code?
I figured out the problem in the for loop. I am looping through i[2] and then trying to modify it within the loop. this makes it unstable.

TypeError: list indices must be integers, not unicode in python code

I used the split() function to convert string to a list time = time.split() and this is how my output looks like :
[u'1472120400.107']
[u'1472120399.999']
[u'1472120399.334']
[u'1472120397.633']
[u'1472120397.261']
[u'1472120394.328']
[u'1472120393.762']
[u'1472120393.737']
Then I tried accessing the contents of the list using print time[1] which gives the index out of range error (cause only a single value is stored in one list). I checked questions posted by other people and used print len(time). This is the output for that:
1
[u'1472120400.107']
1
[u'1472120399.999']
1
[u'1472120399.334']
1
[u'1472120397.633']
1
[u'1472120397.261']
1
[u'1472120394.328']
1
[u'1472120393.762']
1
[u'1472120393.737']
I do this entire thing inside a for loop because I get logs dynamically and have to extract out just the time.
This is part of my code:
line_collect = lines.collect() #spark function
for line in line_collect :
a = re.search(rx1,line)
time = a.group()
time = time.split()
#print time[1] #index out of range error which is why I wrote another for below
for k in time :
time1 = time[k]#trying to put those individual list values into one variable but get type error
print len(time1)
I get the following error :
time1 = time[k]
TypeError: list indices must be integers, not unicode
Can someone tell me how to read each of those single list values into just one list so I can access each of them using a single index[value]. I'm new to python.
My required output:
time =['1472120400.107','1472120399.999','1472120399.334','1472120397.633','1472120397.261','1472120394.328','1472120393.762','1472120393.737']
so that i can use time[1] to give 1472120399.999 as result.
Update: I misunderstood what you wanted. You have the correct output already and it's a string. The reason you have a u before the string is because it's a unicode string that has 16 bits. u is a python flag to distinguish it from a normal string. Printing it to the screen will give you the correct string. Use it normally as you would any other string.
time = [u'1472120400.107'] # One element just to show
for k in time:
print(k)
Looping over a list using a for loop will give you one value at a time, not the index itself. Consider using enumerate:
for k, value in enumerate(time):
time1 = value # Or time1 = time[k]
print(time1)
Or just getting the value itself:
for k in time:
time1 = k
print(time1)
--
Also, Python is zero based language, so to get the first element out of a list you probably want to use time[0].
Thanks for your help. I finally got the code right:
newlst = []
for line in line_collect :
a = re.search(rx1,line)
time = a.group()
newlst.append(float(time))
print newlst
This will put the whole list values into one list.
Output:
[1472120400.107, 1472120399.999, 1472120399.334, 1472120397.633,
1472120397.261, 1472120394.328, 1472120393.762, 1472120393.737]

Python remove odd numbers and print only even

user = int(raw_input("Type 5 numbers"))
even = []
def purify(odd):
for n in odd:
even.append(n)
if n % 2 > 0:
print n
print purify(user)
Hello I am a beginner and I would like to understand what is wrong with this code.
The User chose 5 numers and I want to print the even numbers only.
Thanks for helping
There are a few problems:
You can't apply int to an overall string, just to one integer at a time.
So if your numbers are space-separated, then you should split them into a list of strings. You can either convert them immediately after input, or wait and do it within your purify function.
Also, your purify function appends every value to the list even without testing it first.
Also, your test is backwards -- you are printing only odd numbers, not even.
Finally, you should return the value of even if you want to print it outside the function, instead of printing them as you loop.
I think this edited version should work.
user_raw = raw_input("Type some space-separated numbers")
user = user_raw.split() # defaults to white space
def purify(odd):
even = []
for n in odd:
if int(n) % 2 == 0:
even.append(n)
return even
print purify(user)
raw_input returns a string and this cannot be converted to type int.
You can use this:
user = raw_input("Input 5 numbers separated by commas: ").split(",")
user = [int(i) for i in user]
def purify(x):
new_lst = []
for i in x:
if i % 2 == 0:
new_lst.append(i)
return new_lst
for search even
filter would be the simplest way to "filter" even numbers:
output = filter(lambda x:~x&1, input)
def purify(list_number):
s=[]
for number in list_number:
if number%2==0:
s+=[number]
return s