Apply function to each element of a list
Using the built-in standard library map
:
>>> mylis = ['this is test', 'another test']
>>> list(map(str.upper, mylis))
['THIS IS TEST', 'ANOTHER TEST']
In Python 2.x, map
constructed the desired new list by applying a given function to every element in a list.
In Python 3.x, map
constructs an iterator instead of a list, so the call to list
is necessary. If you are using Python 3.x and require a list the list comprehension approach would be better suited.
Apply function to all items in a list Python
You can use map
approach:
list(map(myCoolFunction, my_list))
This applies defined function on each value of my_list
and creates a map object (3.x). Calling a list()
on it creates a new list.
apply a function over each element of an iterable with sublists
Sounds like recursion should be able to solve that:
a = [1,2,3]
b = [[1,2,3], [4,5,6]]
c = [[[1,2,3], [4,5,6]], [[7,8,9], [10,11,12]]]
f = lambda x : x+1
def apply(iterable, f):
# suggestion by Jérôme:
# from collections.abc import Iterable and use
# isinstance(iterable, collections.abc.Iterable) so it works for tuples etc.
if isinstance(iterable, list):
# apply function to each element
return [apply(w, f) for w in iterable]
else:
return f(iterable)
print(apply(a, f)) # [2,3,4]
print(apply(b, f)) # [[2,3,4],[5,6,7]]
print(apply(c, f)) # [[[2,3,4],[5,6,7]],[[8,9,10],[11,12,13]]]
How to apply a function to each element in a list, then make a list of the outputs?
In factors
function, you are appending the factors themselves to list2
but as you want nested list of factors, you should create another list and append that to list2
instead. Changed code would look something like this.
import math
list1 = []
list2 = []
def factors(num1):
factor_list = []
for x in range(1, int(math.sqrt(num1) + 1)):
if num1 % x == 0:
factor_list.append(int(x))
factor_list.append(int(num1/x))
factor_list.sort()
list2.append(factor_list)
print("enter a number:")
number = int(input())
for m in range(1, int(math.sqrt(number) + 1)):
if number % m == 0:
list1.append(int(m))
list1.append(int(number/m))
list1.sort()
for y in list1:
factors(y)
print(list2)
Also, since you've already wrote the factors
function, you can use it for factorizing the input number itself instead of writing the same code again. So a better version of the same code is:
import math
def factors(num1):
factor_list = []
for x in range(1, int(math.sqrt(num1) + 1)):
if num1 % x == 0:
factor_list.append(int(x))
factor_list.append(int(num1/x))
factor_list.sort()
return factor_list
print("enter a number:")
number = int(input())
list1 = factors(number)
list2 = [factors(x) for x in list1]
print(list2)
Following up on the comment, if you want to include only on those elements which have length 2, you can use another list comprehension for that:
list2 = [x for x in list2 if len(x)==2]
Apply function to all the elements (lists of strings) of a column to convert into floats
I think the error is due to the presence of NaN
values in the column c
, one way to fix this is to remove the NaN values before applying the map function:
df['c'] = df['c'].dropna().apply(lambda x: list(map(float, x)))
Apply function to every element in a list in a df column
First, you should never use a bare except
.
Second, because your function translates a single word and returns the translated word and the detected language as a tuple, it would be difficult and tedious to achieve your desired output of a list of translated words and a single detected language. Instead, modify your function to do so:
import googletrans
def detect_and_translate(lst):
translator = Translator()
target_lang = 'en'
try:
result_lang = translator.detect(lst[0])
except Exception: # should be the specific exception that can occur
return lst, result_lang
translations = []
for text in lst:
translated_text = translator.translate(text, dest=target_lang)
translations.append(translated_text.text)
return translations, result_lang
Usage:
In [4]: googletrans.__version__
Out[4]: '4.0.0-rc.1'
In [5]: df[["topics_en", "language"]] = df.top_topics.apply(detect_and_translate).apply(pd.Series)
In [6]: df
Out[6]:
label top_topics topics_en language
0 adverts [werbung, geschenke] [advertising, gifts] Detected(lang=de, confidence=None)
Note that googletrans.Translator
has a language detection method. It doesn't work in 3.0.0
but if you pip install googletrans==4.0.0rc1
it will.
Note also that in order for this to work, you must assume that all words in a given list are the same language. If that's not an assumption you can make, you'll need to figure something else out.
how to apply function to a list element within a list of lists?
Remember that your element
array is actually a reference into the original list. If you modify the list, you'll modify global_tp_old
as well.
Something like this, although you may need to change the dataframe indexing depending on whether you're looking for rows or columns.
global_tp_old = [[2, 1, 0.8333595991134644],[2, 1, 0.8530714511871338]]
global_tp_new = []
for element in global_tp_old:
element = [df_unique.iloc[element[0]]] + element[1:]
global_tp_new.append(element)
Apply a function to each element of each dataframe in a list
Apply the same functions using lapply
. This applies both centered and scaled function together.
lapply(l, function(y) apply(y, 2, function(x) {
x = x - mean(x)
x/sqrt(sd(x))
}))
#[[1]]
# A B
#[1,] -0.5946036 -0.8408964
#[2,] 0.5946036 0.8408964
#[[2]]
# A B
#[1,] -1.3201676 -1.3201676
#[2,] -0.4400559 -0.4400559
#[3,] 0.4400559 0.4400559
#[4,] 1.3201676 1.3201676
If you want them separately
centered <- lapply(l, function(y) apply(y, 2, function(x) x - mean(x)))
scaled <- lapply(centered, function(y) apply(y, 2, function(x) x/sqrt(sd(x))))
Apply function on all elements of list and return a new list based on function's return type
Three problems:
- You want
\ x ->
instead of\ list x ->
. map
will give you a list ofBool
s. If you want to know if they're all true, then you need to either useall
instead, or wrap the result inand
.- Unless
Vector
is an alias for some weird function type, you probably meantdistance x y
ordistance (x,y)
instead ofdistance (x y)
.
Related Topics
Checking Running Python Script Within the Python Script
Usb Automatic Detection in Python for Linux Env
Distributing Ruby/Python Desktop Apps
Cannot Open Include File: 'Io.H': No Such File or Directory
Remove Duplicate Dict in List in Python
Why Does This Code for Initializing a List of Lists Apparently Link the Lists Together
Why Is Button Parameter "Command" Executed When Declared
How to Return Two Values from a Function in Python
Writing a Python List of Lists to a CSV File
Unicodedecodeerror Reading Binary Input
Compare Two Files for Differences in Python
Is There Something Wrong with This Python Code, Why Does It Run So Slow Compared to Ruby
Security of Python's Eval() on Untrusted Strings
How to Round to 2 Decimals with Python
Animated Sprite from Few Images
Matplotlib: How to Create Axessubplot Objects, Then Add Them to a Figure Instance
Pip Install MySQL-Python Fails with Environmenterror: MySQL_Config Not Found