Recycling operations in Python similar to R vectorization

丶灬走出姿态 提交于 2021-02-08 07:43:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!