How to convert numeric string from a sublist in Python - python

I'm a freshie. I would like to convert a numeric string into int from a sublist in Python. But not getting accurate results. 😔
countitem = 0
list_samp = [['1','2','blue'],['1','66','green'],['1','88','purple']]
for list in list_samp:
countitem =+1
for element in list:
convert_element = int(list_samp[countitem][0])
list_samp[countitem][1] = convert_element

You can do it like this:
list_samp = [['1','2','blue'],['1','66','green'],['1','88','purple']]
me = [[int(u) if u.isdecimal() else u for u in v] for v in list_samp]
print(me)

The correct way to do it:
list_samp = [['1','2','blue'],['1','66','green'],['1','88','purple']]
list_int = [[int(i) if i.isdecimal() else i for i in l] for l in list_samp]
print(list_int)

Let's go through the process step-by-step
countitem = 0
list_samp = [['1','2','blue'],['1','66','green'],['1','88','purple']]
#Let's traverse through the list
for list in list_samp: #gives each list
for i in range(len(list)): # get index of each element in sub list
if list[i].isnumeric(): # Check if all characters in the string is a number
list[i] = int(list[i]) # store the converted integer in the index i

Related

How do I use a while loop to access all the 2nd elements of lists which are the values stored in a dictionary?

If I have a dictionary like this, filled with similar lists, how can I apply a while loo tp extract a list that prints that second element:
racoona_valence={}
racoona_valence={"rs13283416": ["7:87345874365-839479328749+","BOBB7"],\}
I need to print the part that says "BOBB7" for 2nd element of the lists in a larger dictionary. There are ten key-value pairs in it, so I am starting it like so, but unsure what to do because all the examples I can find don't relate to my problem:
n=10
gene_list = []
while n>0:
Any help greatly appreciated.
Well, there's a bunch of ways to do it depending on how well-structured your data is.
racoona_valence={"rs13283416": ["7:87345874365-839479328749+","BOBB7"], "rs13283414": ["7:87345874365-839479328749+","BOBB4"]}
output = []
for key in racoona_valence.keys():
output.append(racoona_valence[key][1])
print(output)
other_output = []
for key, value in racoona_valence.items():
other_output.append(value[1])
print(other_output)
list_comprehension = [value[1] for value in racoona_valence.values()]
print(list_comprehension)
n = len(racoona_valence.values())-1
counter = 0
gene_list = []
while counter<=n:
gene_list.append(list(racoona_valence.values())[n][1])
counter += 1
print(gene_list)
Here is a list comprehension that does what you want:
second_element = [x[1] for x in racoona_valence.values()]
Here is a for loop that does what you want:
second_element = []
for value in racoona_valence.values():
second_element.append(value[1])
Here is a while loop that does what you want:
# don't use a while loop to loop over iterables, it's a bad idea
i = 0
second_element = []
dict_values = list(racoona_valence.values())
while i < len(dict_values):
second_element.append(dict_values[i][1])
i += 1
Regardless of which approach you use, you can see the results by doing the following:
for item in second_element:
print(item)
For the example that you gave, this is the output:
BOBB7

How to find the highest value element in a list with reference to a dictionary on python

How do I code a function in python which can:
iterate through a list of word strings which may contain duplicate words and referencing to a dictionary,
find the word with the highest absolute sum, and
output it along with the corresponding absolute value.
The function also has to ignore words which are not in the dictionary.
For example,
Assume the function is called H_abs_W().
Given the following list and dict:
list_1 = ['apples','oranges','pears','apples']
Dict_1 = {'apples':5.23,'pears':-7.62}
Then calling the function as:
H_abs_W(list_1,Dict_1)
Should give the output:
'apples',10.46
EDIT:
I managed to do it in the end with the code below. Looking over the answers, turns out I could have done it in a shorter fashion, lol.
def H_abs_W(list_1,Dict_1):
freqW = {}
for char in list_1:
if char in freqW:
freqW[char] += 1
else:
freqW[char] = 1
ASum_W = 0
i_word = ''
for a,b in freqW.items():
x = 0
d = Dict_1.get(a,0)
x = abs(float(b)*float(d))
if x > ASum_W:
ASum_W = x
i_word = a
return(i_word,ASum_W)
list_1 = ['apples','oranges','pears','apples']
Dict_1 = {'apples':5.23,'pears':-7.62}
d = {k:0 for k in list_1}
for x in list_1:
if x in Dict_1.keys():
d[x]+=Dict_1[x]
m = max(Dict_1, key=Dict_1.get)
print(m,Dict_1[m])
try this,
key, value = sorted(Dict_1.items(), key = lambda x : x[1], reverse=True)[0]
print(f"{key}, {list_1.count(key) * value}")
# apples, 10.46
you can use Counter to calculate the frequency(number of occurrences) of each item in the list.
max(counter.values()) will give us the count of maximum occurring element
max(counter, key=counter.get) will give the which item in the list is
associated with that highest count.
========================================================================
from collections import Counter
def H_abs_W(list_1, Dict_1):
counter = Counter(list_1)
count = max(counter.values())
item = max(counter, key=counter.get)
return item, abs(count * Dict_1.get(item))

adding value to my matrix but the result shows an error

I am trying to append a list of 4 letters in my number as a [[a, b, c, d]] type of list.
I am looping through a list and appending the letter to a temp list and then appending it to my main list to make it into a matrix. However, the main list is only storing the number (8, 26) for some reason
ciphertext = "asfgasgsaga"
counter = 0
templist = []
xyz = []
for abc in ciphertext:
if(counter == 5):
print(templist)
xyz.append(templist)
templist.clear()
counter = 0
else:
templist.append(abc);
counter += 1
print(xyz)
The result is for some reason giving [[8, 26]]
The result is not the same as your expected because there some concepts that you need to know about objects in Python:
Immutable Objects: int, float, complex, string, tuple, frozen set, bytes. These kind of data types can't be changed the value after it is created. So that when we assign to another variable, it will copy the value to new variable. E.g:
a = 123
b = a
a = 456
print(b) #123
Mutable Objects: list, dict, set, byte array. These can be changed the value after it is created. And when you assign to another variable, it basically just assign the reference to previous variable like so:
a = []
b = a
a.append(123)
print(b) #[123]
So back to your problem, you're using list to create a list with 4 characters and then append it into another list, it's not append the expected list but instead a reference to it. That's why you got unexpected result.
And about the logic of your code, there are something go wrong, because when counter you will miss 1 character. You actually can switch to use slicing in Python:
ciphertext = "asfgasgsaga"
xyz = [ciphertext[start:start + 4] for start in range(0, len(ciphertext), 4)]
print(xyz) #['asfg', 'asgs', 'aga']
I'm using List Comprehension to append to xyz instead of call append function, create step like: 0:4, 4:8, 8:12, ... voila
Hope that helpful for you.
Just as #zvone says, don's use the same array and clear it, because they ref the same memory;
ciphertext = "asfgasgsaga"
counter = 0
templist = []
xyz = []
for abc in ciphertext:
if(counter == 4):
print(templist)
xyz.append(templist)
templist = [] # <--- use a new empty array
counter = 0
else:
templist.append(abc);
counter += 1
print(xyz)
Also, the correct logic(handle the letters less than 4) should be:
ciphertext = "asfgasgsaga"
counter = 0
templist = []
xyz = []
for abc in ciphertext:
templist.append(abc);
counter += 1
if(counter == 4):
print(templist)
xyz.append(templist)
templist = []
counter = 0
if templist:
xyz.append(templist)
print(xyz)
Just see #Toan Quoc Ho's answer, which should make more sense. Just leave the answer here to compare your origin logic.

Insert value at multiple specified positions into a python string/array

I would like to insert values at multiple specified positions into a python string/array.
eg for my input string : SARLSAMLVPVTPEVKPK
at specified positions: 1,5,12
the desired output: S*ARLS*AMLVPVT*PEVKPK
I tried:
seq="SARLSAMLVPVTPEVKPK" #string
pos=[1,5,12] #positions
arr=list(seq) #convert string to array
arr.insert(pos,"*") # NOT WORK!
arr.insert(pos[0],"*")
print(''.join(arr))
It seems I can only insert a position at a time and thus the indices of the specified positions for the next insert would have to change.
Is there an elegant way of doing this or would I have to loop through the insert positions adding +1 for each additional insert position?
I hope this make sense!
Many thanks,
Curly.
Just insert them in reverse order:
seq="SARLSAMLVPVTPEVKPK" #string
pos=[1,5,12] #positions
arr = list(seq)
for idx in sorted(pos, reverse=True):
arr.insert(idx,"*")
print ''.join(arr)
Something like this would do:
seq="SARLSAMLVPVTPEVKPK" #string
pos=[1,5,12] #positions
arr=list(seq) #convert string to array
_ = map(lambda k: arr.insert(k, "*"), pos[::-1])
print(''.join(arr))
or
seq="SARLSAMLVPVTPEVKPK" #string
pos=[1,5,12] #positions
arr=list(seq) #convert string to array
for k in pos[::-1]:
arr.insert(k, "*")
print(''.join(arr))
Simple Way:
temp = ""
temp += seq[:pos[0]]
temp += "*"
for i in range(1,len(pos)):
temp += seq[pos[i-1]:pos[i]]
temp += "*"
temp += seq[pos[-1]:]
print (temp) # 'S*ARLS*AMLVPVT*PEVKPK'

Python list, take even elements and odd elements to their own respective new lists

I am working on a problem wherein I paste a set of numbers, and I want to put the even and odd list elements from these numbers and put them in their own list, then add them together for a 3rd list.
Here is my code:
#list of numbers
start = """
601393 168477
949122 272353
944397 564134
406351 745395
281988 610822
451328 644000
198510 606886
797923 388924
470601 938098
578263 113262
796982 62212
504090 378833
"""
x = start.split()
#turn string into list elements then append to a list
step_two = []
step_two.append(x)
print step_two
# doublecheck that step_two is a list with all the numbers
step_three = step_two[1::2]
#form new list that consists of all the odd elements
print step_three
#form new list that consists of all the even elements
step_four = step_two[0::2]
print step_four
#add ascending even/odd element pairs together and append to new list
final_step = [x + y for x, y in zip(step_three, step_four)]
print final_step
This code yields these results:
"""
"Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
[['601393', '168477', '949122', '272353', '944397', '564134', '406351', '745395'
, '281988', '610822', '451328', '644000', '198510', '606886', '797923', '388924'
, '470601', '938098', '578263', '113262', '796982', '62212', '504090', '378833']
]
[]
[['601393', '168477', '949122', '272353', '944397', '564134', '406351', '745395'
, '281988', '610822', '451328', '644000', '198510', '606886', '797923', '388924'
, '470601', '938098', '578263', '113262', '796982', '62212', '504090', '378833']
]
[]
"""
Why is my list in step_three and step_four not working? I am not sure why my [::] functions aren't registering.
Thanks in advance for any advice.
You were too explicit here in step two:
x = start.split()
#turn string into list elements then append to a list
step_two = []
step_two.append(x)
x is already the list you need. step_two creates a new list and adds the previous list to it, so instead of ['601393', '168477',...], you have [['601393', '168477',...]].
To fix this, simply call the split string step_two and proceed from there:
step_two = start.split()
The reason your lists don't split the numbers into odd and even is that your code assumes that the list alternates between them - you take every other index for each list generation, but the numbers aren't arranged that way in the original string.
You'll need to do an 'evenness' test:
step_two = start.split()
step_three = []
step_four = []
for item in step_two:
if int(item) % 2: # If it divides evenly by two, it returns 0, or False
step_three.append(item)
else:
step_four.append(item)
The lists step_three and step_four will now correctly contain only odds or evens.
Here is how I would generate the odd list, hope it helps!
import sys
# Provided main(), calls mimic_dict() and mimic()
def main():
#list of numbers
start = '601393 168477 949122 272353 944397 564134 406351 745395 281988 610822 451328 644000 198510 606886 797923 388924470601 938098 578263 113262 796982 62212 504090 378833'
x = start.split()
#turn string into list elements then append to a list
step_two = []
# gives you 23 items in your list "step_two" instead of 1 item with original append on it's own
for s in x:
step_two.append(s)
#print (step_two)
# print (step_two)
# doublecheck that step_two is a list with all the numbers
i = 1
step_three_odd_list = []
while i < len(step_two):
currentodditem = step_two[i]
step_three_odd_list.append(currentodditem)
i = i + 2
#form new list that consists of all the odd elements
print (step_three_odd_list)
if __name__ == '__main__':
main()
The [::] that you have going on are extended slices, not tests for even and odd:
https://docs.python.org/release/2.3.5/whatsnew/section-slices.html
Also, since those numbers are in a string, when you split them you end up with strings, not integers that you test with math. So, you need to convert them to integers.
This post clued me in on a quick even/odd test: Check if a number is odd or even in python
This code seems to do what you want, if I understand it correctly:
start = """
601393 168477
949122 272353
944397 564134
406351 745395
281988 610822
451328 644000
198510 606886
797923 388924
470601 938098
578263 113262
796982 62212
504090 378833
"""
# List comprehension to generate a list of the numbers converted to integers
step_two = [int(x) for x in start.split()]
# Sort the list
step_two.sort()
# Create new lists for even and odd
even_numbers = []
odd_numbers = []
# For each item in the list, test for even or odd and add to the right list
for number in step_two:
if (number % 2 == 0):
#even
even_numbers.append(number)
else:
#odd
odd_numbers.append(number)
print(even_numbers)
print(odd_numbers)
final_step = [x + y for x, y in zip(even_numbers, odd_numbers)]
print(final_step)
You can use list comprehensions to create two lists odd and even :
import itertools
start = """
601393 168477
949122 272353
944397 564134
406351 745395
281988 610822
451328 644000
198510 606886
797923 388924
470601 938098
578263 113262
796982 62212
504090 378833
"""
lst = start.split()
even = [int(i) for i in lst if int(i) % 2 == 0]
odd = [int(i) for i in lst if int(i) % 2 != 0]
Then you can zip these 2 lists but as even and odd are not the same length, you have to use itertools.zip_longest() in Python 3 and itertools.izip_longest() in Python 2. You will then have a list of tuples:
final_step = [i for i in itertools.zip_longest(even,odd)]
[(949122, 601393),
(564134, 168477),
(281988, 272353),
(610822, 944397),
(451328, 406351),
(644000, 745395),
(198510, 797923),
(606886, 470601),
(388924, 578263),
(938098, 378833),
(113262, None),
(796982, None),
(62212, None),
(504090, None)]
You can create the third list result to sum() the values using an other list comprehension but you have to make sure not to try to sum the tuples where one value is None.
result = [sum(e) if e[1] is not None else e[0] for e in final_step]
The final output:
[1550515,
732611,
554341,
1555219,
857679,
1389395,
996433,
1077487,
967187,
1316931,
113262,
796982,
62212,
504090]

Categories

Resources