列表理解中有多个变量? [英] multiple variables in list comprehension?

查看:53
本文介绍了列表理解中有多个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从多字段字符串列表中创建列表列表,并想知道是否有可能这样做.

I want to create a list of lists from a list of multi-field strings and wonder if it is possible to do so in a comprehension.

输入:

inputs = ["1, foo, bar", "2, tom, jerry"]

所需的输出:

[[1, "foo", "bar"], [2, "tom", "jerry"]]

容易理解地将字符串拆分:

Splitting the string in a comprehension is easy:

>>> [s.split(",") for s in inputs]
[['1', ' foo', ' bar'], ['2', ' tom', ' jerry']]

但是在将字符串在理解范围内拆分后,我很难弄清楚如何访问列,​​因为它似乎需要变量赋值.以下是无效的Python,但可以说明我在寻找什么:

But I'm having trouble figuring out how to access the columns after the string has been split inside the comprehension, because it would seem to require a variable assignment. The following are not valid Python, but illustrate what I'm looking for:

[[int(x), y.strip(), z.strip() for x,y,z = s.split(",")] for s in inputs]
    or
[[int(v[0]), v[1].strip(), v[2].strip() for v = s.split(",")] for s in inputs]

是否有一种方法可以在理解内分配变量,以便输出可以由变量的功能组成?一个循环是微不足道的,但通过转换输入生成一个列表确实看起来像是一项理解性"任务.

Is there a way to assign variables inside a comprehension so that the output can be composed of functions of the variables? A loop is trivial, but generating a list by transforming inputs sure seems like a "comprehension-ish" task.

outputs = []
for s in inputs:
    x,y,z = s.split(",")
    outputs.append([int(x), y.strip(), z.strip()])

推荐答案

您可以使用列表理解中的两个 for 子句来做到这一点.第一个遍历列表中的项目.第二个遍历一个单项列表,该列表包含从拆分字符串得到的列表(这是必需的,因此我们可以将其解压缩为三个单独的变量).

You can do this with two for clauses in your list comprehension. The first iterates over the items in the list. The second iterates over a single-item list containing the list derived from splitting the string (which is needed so we can unpack this into three separate variables).

[[int(x), y.strip(), z.strip()] for s in inputs for (x, y, z) in [s.split(",")]]

for 子句的排列顺序有点违反直觉,但与您将其作为嵌套的 for 循环的编写方式相匹配.

The for clauses go in a somewhat counterintuitive order, but it matches the way you'd write it as nested for loops.

乔恩·夏普(Jon Sharpe)对嵌套理解(实际上是生成器表达式)的使用很相似,而且可能更清晰.对我来说,使用多个 for 子句总是让人感到困惑.主要是我想看看是否可以在这里使用它.

Jon Sharpe's use of a nested comprehension (generator expression, actually) is similar and probably clearer. The use of multiple for clauses always seems confusing to me; mainly I wanted to see if I could make use of it here.

这篇关于列表理解中有多个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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