python - 转换列表中的字符串

标签 python string list integer tuples

如何转换列表中的字符串返回一个包含字符串元素和字符串长度的列表? 就像 add_sizes([str]) -> [(str, int)]

这是我做的:

def add_sizes(strings):
    for i in strings:
        return [(i, (len(i)))]

但这只适用于一个字符串,如果我有多个字符串怎么办?

最佳答案

使用list_comprehension

>>> l = ['foo', 'bar', 'j', 'mn']
>>> [(i,len(i)) for i in l]
[('foo', 3), ('bar', 3), ('j', 1), ('mn', 2)]

将其定义为一个单独的函数。

def add_sizes(l):
    return [(i,len(i)) for i in l]

关于python - 转换列表中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29329650/

相关文章:

list - 为什么 shuffle' 函数需要一个 Int 参数?

python - 将数据框分解为子集/组的新数据框。从其他数据框创建数据子集/组的新数据框

python - Tensorflow 将图加载到特定范围

c++ - 检查给定字符串是否等效于给定字符串集中至少一个字符串的有效方法

c - C中的字符串初始化

php - 如何在 php 中对字符串数组进行排序? [这里的字符串是路径。例如/root/mandy/a.pdf, b.pdf & c.pdf

python - 如何在不使用嵌套 for 循环的情况下迭代两个列表?

javascript - 在 For 循环中探索 javascript 中的树结构

python - R Reticulate - 以编程方式将定义的变量从 Python 环境移动到 R

python - 使用 boto 在 S3 上的子桶中插入项目