本文介绍了Perl等同于(Python-)列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找在Perl中表达此Python代码段的方法:

I'm looking for ways to express this Python snippet in Perl:

data = {"A": None, "B": "yes", "C": None}
key_list = [k for k in data if data[k]]  
# in this case the same as filter(lambda k: data[k], data) but let's ignore that

所以从一种角度来看,我只想要键值为 None undef 的键.用另一种方式来看,我想要的是与清单理解的简洁Perl等效项有条件的.

So looking at it one way, I just want the keys where the values are None or undef. Looking at it another way, what I want is the concise perl equivalent of a list comprehension with conditional.

推荐答案

我认为您想要 :

#!/usr/bin/env perl
use strict;
use warnings;

my %data = ( A => undef, B => 'yes', C => undef );

my @keys = grep { defined $data{$_} } keys %data;

print "Key: $_\n" for @keys;

我还认为输入速度太慢,因此在发布答案之前应该重新加载页面.顺便说一句,值0undef可能是处理 null 值的好方法,但请确保您记住正在使用的值.错误值和未定义值在Perl中不是同一回事.需要说明的是:undef在布尔测试中返回false,但0也是.如果0是有效值,那么您要显式测试定义性,而不仅仅是真实性. (我之所以这样提,是因为James参加了0,而我却选择了另一种方式,所以您可能不知道这是否重要.)

I also think that I type too slowly, and that I should reload the page before posting answers. By the way, either a value of 0 or undef can be a good way to handle null values, but make sure you remember which you're using. A false value and and undefined value aren't the same thing in Perl. To clarify: undef returns false in a boolean test, but so does 0. If 0 is a valid value, then you want to explicitly test for definedness, not simply truth. (I mention it because James went for 0 and I went the other way, and you may or may not know if it matters.)

这篇关于Perl等同于(Python-)列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 14:44