I want to join the elements in this list, L, and store the result in a variable k.
such that
L=[1,1,0,1,0]
k=11010
If you are using Python (like I suspect [and a previous question of yours was on python]), this isn't very difficult.
x = [0,1,2,3,4]
xs = ""
for i in x:
xs+=str(i)
print(xs) #As string
If you want to get it as an integer, you can add
k = int(xs)
As a function, this would be:
def makeIntFromList(x):
xs = ""
for i in x:
xs+=i
return int(xs)
Or, you can use join().
def joinElementsToInt(x):
return int("".join([str(i) for i in x]))
In javascript:
var k, L=[1,1,0,1,0];
k = L.join("");
will do the job.
Related
I'm trying to learn about lambda functions, I'm would like the code to:
add a slash '/' to the end of a string in list 'techCodeList'
add and append every item in 'finishList' to the every entry in 'techCodeList', appending to 'combinedCodeList' every time (so combinedCodeList = ['a/ABUL', 'a/BEL', 'a/PBL'] etc)
I could do it using other methods but I want to try using lambda, so would it be viable and if so how would I do it? My code is below:
#example shortened
class myClass:
def __init__(self):
self.techCodeList = ('a','b','c')
def applyCodes(self):
self.combinedCodeList = list()
finishList = ["ABUL","BEL","PBL","PBUL","ABL","SBL","SBSL","SBUL","PNP","SNP","PCP","SCP","NBP","ASP","ACP","SAL","SAS","AMB","CBP","HBN","MBL","MWL","HBB","SPE","PBUL/SAMPLE"]#list to append to techcodelist
len1 = len(self.combinedCodeList)
arrayCounter = 0
for i in self.techCodeList:
for _ in finishList:
print (arrayCounter)
self.techCodeList = list(map(lambda orig_string: orig_string + '/', self.techCodeList[arrayCounter]))
self.techCodeList = list(map(lambda orig_string: orig_string + finishList[arrayCounter], self.techCodeList[arrayCounter]))
self.combinedCodeList.append(self.techCodeList[arrayCounter])
if arrayCounter == len(self.techCodeList) - 1:
break
arrayCounter = arrayCounter + 1
print (self.combinedCodeList)
myClass()
And here is the result in the combinedCodeList:
['aABUL', '/BEL', '/BEL', '/BEL']
If you have any other suggestions for good habits or suggestions for my code please feel free to leave them too, I'm still very much learning. Thanks.
If I understood correctly you want to create an exchaustive combinations between all the entries from the tech code and finish lists.
For that you can use list comprehension like below:
tech_code_list = ["a", "b", "c"]
finish_list = ["ABUL","BEL","PBL","PBUL","ABL","SBL","SBSL","SBUL","PNP","SNP","PCP","SCP","NBP","ASP","ACP","SAL","SAS","AMB","CBP","HBN","MBL","MWL","HBB","SPE","PBUL/SAMPLE"]
combined_code_list = [
tech_code + "/" + finish for tech_code in tech_code_list for finish in finish_list
]
print(combined_code_list)
# will print: ['a/ABUL', 'a/BEL', 'a/PBL', 'a/PBUL', ... ]
iterools.product gives you all pairwise combinations from two lists. As you want to use lambda we do that in the map function
from itertools import product
list(map(lambda p: p[0] + '/' + p[1], product(tech_code_list, finish_list)))
output:
['a/ABUL',
'a/BEL',
'a/PBL',
'a/PBUL',
'a/ABL',
...
]
My code:
def shorter(lst):
if len(lst) == 0:
return []
if lst[0] in lst[1:]:
lst.remove(lst[0])
shorter(lst[1:])
return lst
print shorter(["c","g",1,"t",1])
Why does it print ["c","g",1,"t",1] instead of ["c","g","t",1]
For a recursive method, what you can do is check a specific index in the again as you have it. If we remove the current element, we want to stay at the same index, otherwise we want to increase the index by one. The base case for this is if we are looking at or beyond the last element in the array since we don't really need to check it.
def shorter(lst, ind=0):
if ind >= len(lst)-1: #Base Case
return lst
if lst[ind] in lst[ind+1:]:
lst.pop(ind)
return shorter(lst,ind)
return shorter(lst, ind+1)
#Stuff to test the function
import random
x = [random.randint(1,10) for i in range(20)]
print(x)
x = shorter(x)
print(x)
Another way to solve this in a single line is to convert the list into a set and then back into a list. Sets have only unique values, so we can use that property to remove any repeating elements.
import random
x = [random.randint(1,10) for i in range(20)]
print(x)
x = list(set(x)) #Converts to set and back to list
print(x)
A possible recursive solution could be:
def shorter(lst):
if lst:
if lst[0] in lst[1:]:
prefix = [] # Skip repeated item.
else:
prefix = [lst[0]] # Keep unique item.
return prefix + shorter(lst[1:])
else:
return lst
The previous code can also be compacted to:
def shorter(lst):
if lst:
return lst[0:(lst[0] not in lst[1:])] + shorter(lst[1:])
else:
return lst
and the function body can also be reduced to a one-liner:
def shorter(lst):
return (lst[0:(lst[0] not in lst[1:])] + shorter(lst[1:])) if lst else lst
or even:
def shorter(lst):
return lst and (lst[0:(lst[0] not in lst[1:])] + shorter(lst[1:]))
I am trying to write a function that returns a string that looks like this (2,3|5,6|8,9), but my function on returns a blank string
numbers = [(4,5,6),(1,2,3),(7,8,9)]
def get_numbers(x):
mystring = ""
x = sorted(x)
for n in x:
if mystring is not "":
mystring+="|"
mystring+",".join(str(z) for z in n[1:])
return mystring
How can I fix this?
There's a tiny bug. You typed mystring= instead of mystring +=
numbers = [(4,5,6),(1,2,3),(7,8,9)]
def get_numbers(x):
mystring = ""
x = sorted(x)
for n in x:
if mystring is not "":
mystring+="|"
mystring+=",".join(str(z) for z in n[1:])
return mystring
Use join for change list and tuple to string
values = map(lambda x: x[1:], sorted(numbers))
print "|".join([",".join(map(str, value)) for value in values])
just for fun, a ugly one liner ;-)
'(' + '|'.join([','.join(map(str, l[1:])) for l in numbers]) + ')'
I also added the brackets as you wrote that you want a string looking like this.
I have a list with int values that I would like to add to each other and log the end value. So far I could create a working solution, but it's not so elegant and I would be happy if somebody could show me a smarter solution to achieve the same result.
numberList = (list(string_dict.values()))
numz = []
placeholder = 0
for x in numberList:
numz.append(int(x))
for y in numz:
placeholder = placeholder + y
print (placeholder)
# [1,2,3]
# result: 6
You can use the sum function:
print(sum(int(x) for x in string_dict.values()))
You can take out both loops by using the map() and sum() functions:
numberList = list(string_dict.values())
numz = []
placeholder = 0
numz = list(map(int, numberList))
placeholder = sum(numz)
print (placeholder)
You don't really need to have numberList and numz in there, though. Just do this:
placeholder = sum(map(int, string_dict.values()))
You can use reduce function also:
from functools import reduce
print reduce( (lambda x, y: x + y), string_dict.values() )
Hello so I was wondering how can I 'print' the list of numbers generated by these functions that take the values from the list and squares them. Thanks!!!
def square(list):
return [i ** 2 for i in list]
def square(list):
return map(lambda x: x ** 2, list)
def square(list):
for i in list:
yield i ** 2
def square(list):
ret = []
for i in list:
ret.append(i ** 2)
return ret
Printing a list by using print, for example:
print(', '.join(map(str, square([5,3,2]))
First off, you need different function names, or else when you call it, python will only take the last one.
To answer your question, it is as easy as using a print statement. Simply print the return of the function while using a list as the argument.
square_list = [1,2,3]
print square(square_list)
If you wanted to try a different way, putting the print statement in the function also works.
For example:
def square(list):
print [i ** 2 for i in list] # Instead of return
The downside of this is you cannot store it as a variable or append it to a list later on.
Happy coding!