Multiply or duplicate number in a list. Python - python

How can I duplicate myData. For example
myLen = [1,2,3,4,5,6]
duplicate the number by the length of the 'myLen' and also convert the string to number
myData = ['2']
output:
[2,2,2,2,2,2]

try:
list(map(int,myData*len(myLen)))

What you could do is selecting the index of the element you need in myLen and then apply it to my data:
i = 0
n = myLen[i]
myData = ['2']**n
Of course you could decide what position you need by changing the value of i but make sure it's not greater than the length of myLen otherwise you'll get an error.
Basically the syntax [x]**n creates a list of length n with element x in it.

Related

Pick position of a list based on the position of another list in Python

Im a Python beginner and also new to Stackoverflow cant seem to find a solution to this problem and I have been looking around in weeks. It's an assignment and we cant use inbuild Python functions.
I want to find the position of an item in list A and choose the same position from list B. The item in list A should not be equal to zero. Once done, I have to add the corresponding value in B.
Eg:
A = [0,0,1,1]
B = [25,9,8,3]
A should result in position 2,3
B therefore equals to 8,3
8+3 = 11
Below is what I have tried so far
binary = [0,1,1,0,0,0]
decimal = [32,16,8,4,2,1]
output_decimal = []
for position in range(0, len(binary)):
if binary[position] !=0:
print(position)
I think this is what you wanted.
index = 0
sums = 0
binary = [0,1,1,0,0,0]
decimal = [32,16,8,4,2,1]
for value in binary:
if value == 1:
sums += decimal[index]
index += 1
print(sums)
If you don't need the positions you could just use the following
result = sum([y for x, y in zip(binary, decimal) if x])
In the list comprehension every pair of binary, decimal positions will be iterated and you only keep the decimal ones if the binary is not zero. Then you sum up all kept items.
import numpy as np
binary = np.array([0,1,1,0,0,0])
decimal = np.array([32,16,8,4,2,1])
values = np.where(binary == 1)
output_decimal = decimal[values[0]]
print(output_decimal)
This answer Done By using Numpy Package..
I think you got it. From your code, simply register the positions in the separate list that you created and then sum it up
binary = [0,1,1,0,0,0]
decimal = [32,16,8,4,2,1]
output_decimal = []
for position in range(0, len(binary)):
if binary[position] !=0:
output_decimal.append(decimal[position])
# to add everything
print(sum(output_decimal))
Output gives you: 16+8 = 24
so To find the position of an item in a list and select the same position from another list you can very much use a loop to iterate over the item in the first list. Inside the loop, you then check if the item is not equal to zero, and if it isn't, then you can add the appropriate value in the second list to the output list.
binary = [0,1,1,0,0,0]
decimal = [32,16,8,4,2,1]
output_decimal = []
# Iterate over the items in binary
for i, b in enumerate(binary):
# Check if the item is not equal to zero
if b != 0:
# If it is not, add the corresponding value in decimal to the output list
output_decimal.append(decimal[i])
# Print the output list
print(output_decimal)
so To count the sum of the values in the output list, you can simply use the built-in sum() function, like this:
total = sum(output_decimal)
if you don't want to use sum then you can use the code below:
total = 0
for value in output_decimal:
total += value
I think using enumerate may be good idea in this case:
result = sum([B[i] for i, val in enumerate(A) if val != 0])
print(result)

Python How to search through list X for element Y. Element Y is a list itself whose elements may not be in order as listed in X

I have a list:
X = ['rgb','rg870','rg1200','rg1550']
My second list is:
Y = [870,r,g]
I want to search in the X list and for the combination of Y list even if the order doesn't match and return the element index.
This should return index of 1. #At lest I think its position 1 as the first element is 0?
try this:
import numpy as np
X = ['rgb','rg870','rg1200','rg1550']
Y = ['870','r','g']
result = np.where([sorted(''.join(Y))==sorted(x) for x in X])[0]
print(result)
Code explanation:
''.join(Y) makes you move from a list Y to a string with all elements separated by an empty character.
sorted(''.join(Y)) orders your newly created string.
sorted(x) orders at the same way x, which is iteratively an element of X trhough list comprehension.
By comparing the sorted strings, you ensure that all the characters of Y are contained in the element x in the same number, even if original order was not the same.
Using np.where(_) searches for the position where the matching occurs. Since generally np.where is for matrices, you need to select the first element only: np.where(_)[0].
Finally you print your result which is a list of positions where the matching occurs. If you are sure that only one match occurs, then you may extract it simply doing result = np.where(_)[0][0], thus taking element 0 of your list of results.
# I have a list:
X = ['rgb','rg870','rg1200','rg1550']
# My second list is:
Y = ['870','r','g']
# I want to search in the X list and for the combination
# of Y list even if the order doesn't match and return the element index.
# This should return index of 1. #At lest I think its
# position 1 as the first element is 0?
# You don't mind if I use more descriptive variable names?
def find_combo(full_ids,segments):
for idx,full_id in enumerate(full_ids):
is_match = True
for segment in segments:
if segment in full_id:
pass
else:
is_match = False
break
if is_match:
return idx
else:
continue
find_combo(X,Y)
>>> 1

Adding string values together that are elements in a list

How would I go about doing the following? I need to add the number in the various elements together and assign the total to a new variable. I have been trying for days without much luck. I'm not sure if the numbers have to be split from the letters first?
list = ['2H','4B']
any help would be GREATLY appreciated.
edit:
Thanks for the replies eveyrone. I dont know why I cant get this right it seems like it should be so simple.
I will give you guys some more infomration.
the list below represents to playing cards, the first number or letter is the face value ie: 2 or 3 but can be a 'K' as well which stands for king and the value for that will be ten. the second part is the card suit ie. C for Clubs or H for hearts. I need to add the face value for these two cards together and get the hand total. a More accurate list might look like this.
list1 = ['KH', '10C']
Is this helping. it will help regardless of the number position in them element.
list1 = ['2H','4B']
list1=[word for x in list1 for word in x] #== Split the elements
print(list1)
new_var=0
for value in list1:
try:
value=int(value) #=== Convert to int
new_var+=value #== Add value
except ValueError:
pass
print(new_var)
One approach, using a list comprehension along with re.findall to extract the leading digits from each list entry:
list = ['2H','4B']
nums = [int(re.findall(r'^\d+', x)[0]) for x in list] # [2, 4]
output = sum(nums) # 6
You should avoid using function names as variable names i.e. list =
There are a few ways to do this and I suggest you review the Python documentation on slicing and indexing strings.
l = ['2H','4B']
result = sum(int(x[0]) for x in l)
print(result)
result equals sum of first char of each element of the list. I have converted each indexed element zero to integer to allow addition.
You can also do it the following way:
result = 0
for x in l:
result += int(x[0])
print(result)
You can extract numbers from each string then add them
You can use
total = 0
list = ['2H','4B']
for element in list:
res = [int(i) for i in element.split() if i.isdigit()]
total += sum(res)
print(total)

Finding nth digit of a number in a list

Say you have some nested list
[[4,682,31249,81,523],[321741245,7],[349,25,5]]
where each element can be of any length and the length of each number can vary also. How can one check each individual number for what the first digit from the left contains? As well as continuing through the number to find the 2nd, 3rd, etc digit.
For simplicity, the program just needs to return one digit at a time, i.e. returns 4, then 6 when called again.
Expected output:
4,6,3,8,5,3,7,3,2,5
8,1,1,2,2,4,5
2,2,3,1,9
x=[[4,682,31249,81,523],[321741245,7],[349,25,5]]
x=[item for sublist in x for item in sublist]
max_len=len(str(max(x)))
x=[str(y) for y in x]
def digits(x,index):
digit_list=[]
for num in x:
try:
digit_list.append(num[index])
except:
pass
return digit_list
for index in range(0,max_len):
print(digits(x,index))
Explanation:
1.Intialize x
2.Flat x i.e convert nested list to list
3.Calculate the length of highest number. You can take 'n' on your choice as well. I took it as length of highest number
4.Convert all numbers as string
5.define function digits(). It initializes a list & append single digits according the index called
6.By looping over range(0,max_len/n), call digits() for each index:0-->n
Assuming you are using python do it as:
nestedArr = [[4,682,31249,81,523],[321741245,7],[349,25,5]]
for arr in nestedArr:
firstNums = [str(x)[0] for x in arr]
print(", ".join(firstNums))

How to find the max element from a list of list of float elements?

I have a list of float elements stored in a list. I want to look for the largest element present and do further operations. The list looks like this:
tumor_size = [[2.6,3.65],[],[2.0,2.9,1.7,2.5,1.3]]
I tried answers from this link: Python : find max value and index of a list of list of list
But it did not help.
To look for the largest element, I use this code:
T_stage_list=[]
T_stage = "T2b"
for i in tumor_size:
for j in i:
maxlen = max(tumor_size[j])
if (maxlen>2.0 & maxlen<3.0):
T_stage = "T2a"
T_stage_list.append(T_stage)
This gives me error called "TypeError: list indices must be integers or slices, not float"
However, when I try this:
ltd =[8.7,5.7]
ltdmax = max(ltd)
This successfully gives me 8.7 as a result. So clearly, the float is not the issue. Please help me figure out where I am doing wrong.
In your original code, you are iterating over the elements of the sublist and you are using them as indexes, since the element of the sublist is a float, when you use them as an index i.e. you do tumor_size[2.6], hence you get the error TypeError: list indices must be integers or slices, not float
Also it should be and instead of & to chain conditionals together
To fix this, you would need to iterate over the sublists of each list, and calculate the max given that the list is non-empty
tumor_size = [[2.6,3.65],[],[2.0,2.9,1.7,2.5,1.3]]
#Find max of each sublist given sublist is non-empty
res = [max(li) for li in tumor_size if li]
print(res)
The output will be
[3.65, 2.9]
Or if we go with your original approach, you can get rid of the inner loop, check for maxlen only if the sublist is non-empty, and do your comparison
tumor_size = [[2.6,3.65],[],[2.0,2.9,1.7,2.5,1.3]]
T_stage_list=[]
for i in tumor_size:
#Default value is T0
T_stage = "T0"
#If sublist is non-empty
if i:
#Get max and perform comparison
maxlen = max(i)
if (maxlen>2.0 and maxlen<3.0):
T_stage = "T2a"
else:
T_stage = "T2b"
#Add T_stage
T_stage_list.append(T_stage)
print(T_stage_list)
The output will be
['T2b', 'T0', 'T2a']
Use #Devesh's answer if you want the maximum for all sublists, but you can also use:
print(list(map(max, filter(None, tumor_size))))
maximum of the whole list:
print(max([x for i in tumor_size for x in i]))
Each i in:
for i in tumor_size
is a list.
Each j in:
for j in i
is a float within that list
so when you use the expression:
tumor_size[j]
you're using the float j as an index into the tumor_size list.
That's what's producing your error.
find max elements in each list:
max_elements = [max(l) for l in tumor_size if len(l)>0]
then find the max element in the above list:
print max(max_elements)
mx=[max(l) for l in list_name]
mx=max(mx)
you can also find the index of the max element:
for i in range(len(list_name)):
if mx==ps[i]:
print("The digit is "+str(i))
break

Categories

Resources