问题
I'm attempting to learn more about Python functionality by translating R code while noting the different approaches. There's a recycling rule in R concatenation, if the strings are multiples of each other the evaluator will recycle the smaller object to match the length of the larger. Here's an example:
lttrs <- c("A", "B", "C")
lbl <- "pct"
users <- c(1,2)
If I wanted to combine these three objects to get "Apct1" "Bpct1" "Cpct1" "Apct2" "Bpct2" "Cpct2"
. I can repeat the last object users
to twice the length of the first and R will figure out the rest:
user_indx <- rep(users, each=length(lttrs))
paste0(lttrs, lbl, user_indx)
#[1] "Apct1" "Bpct1" "Cpct1" "Apct2" "Bpct2" "Cpct2"
I have been able to translate the rep(users, each=length(lttrs))
call:
import numpy as np
lttrs = ['A', 'B', 'C']
lbl = ['pct']
users = [1,2]
print np.repeat(users, len(lttrs))
[1 1 1 2 2 2]
I'm struggling to move forward from there.
回答1:
Sounds like what you want is itertools.product, which gives the product of iterables.
from itertools import product
lttrs = ['A', 'B', 'C']
lbl = ['pct']
users = [1,2]
combine = []
for p in product(lttrs, lbl, map(str, users)):
combine.append(''.join(p))
来源:https://stackoverflow.com/questions/33896309/recycling-operations-in-python-similar-to-r-vectorization