等效于 R 的用于 Python 中数字向量的粘贴命令 [英] Equivalent of R's paste command for vector of numbers in Python

查看:21
本文介绍了等效于 R 的用于 Python 中数字向量的粘贴命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题以前肯定有人问过,但我恐怕找不到答案.

This must have been asked before, but I'm afraid I can't find the answer.

在 R 中,我可以写

paste0('s', 1:10)

返回一个包含 10 个字符(字符串)变量的列表:

which returns a list of 10 character (string) variables:

[1] "s1"  "s2"  "s3"  "s4"  "s5"  "s6"  "s7"  "s8"  "s9"  "s10"

我如何在 Python 中简单地做到这一点?我能想到的唯一方法是使用for循环,但必须有一个简单的单行.

How do I do this simply in Python? The only way I can think of is with a for loop, but there must be a simple one-liner.

我尝试过类似的事情

's' + str(np.arange(10))
['s', str(np.arange(10))]

推荐答案

>>> ["s" + str(i) for i in xrange(1,11)]
['s1', 's2', 's3', 's4', 's5', 's6', 's7', 's8', 's9', 's10']

range 适用于 Python 2 和 Python 3,但在 Python 2 中 xrange 的潜在效率更高一些(它是生成器而不是列表).感谢@ytu

range works in both Python 2 and Python 3, but in Python 2 xrange is a little more efficient potentially (it's a generator not a list). Thansk @ytu

这篇关于等效于 R 的用于 Python 中数字向量的粘贴命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆