如何找到一个数组中的哪些元素不在另一个数组中? [英] How do I find which elements in one array aren't in another?

查看:154
本文介绍了如何找到一个数组中的哪些元素不在另一个数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手,因此遇到了基本问题.

I am new to programming and hence I am stuck on a basic level problem.

以下是我编写的用于比较的代码.但是我得到的结果对我来说没有意义.如果有人能告诉我出了什么问题,我将不胜感激.

Following is code I wrote for comparison. But the result I get does not make sense to me. I would appreciate if someone could tell me what is going wrong.

有两个数组:长度不等的@array1@array2.

There are two arrays: @array1 , @array2 of unequal length.

我想比较两者并列出@ array1中不存在的值.

I wish to compare both and list down values not present in @array1.

my %temp = map {$_,$_}@array2;
for (@array1){
next if exists $temp{$_};
open (FILE, ">>/filename") or die "$!";
print FILE "$_\n";
close(FILE);
}

推荐答案

请参阅常见问题解答调整您发布的代码:

#!/usr/bin/perl

use strict; use warnings;

my @x = 1 .. 10;
my @y = grep { $_ % 2 } @x;

my %lookup = map { $_ => undef } @y;

for my $x ( @x ) {
    next if exists $lookup{$x};
    print "$x\n";
}

这篇关于如何找到一个数组中的哪些元素不在另一个数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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