java和python等价于php的foreach($array as $key => $value) [英] java and python equivalent of php's foreach($array as $key => $value)

查看:22
本文介绍了java和python等价于php的foreach($array as $key => $value)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 php 中,我们可以使用这样的关联数组来处理状态名称及其缩写的列表:

In php, one can handle a list of state names and their abbreviations with an associative array like this:

<?php
    $stateArray = array(
        "ALABAMA"=>"AL",
        "ALASKA"=>"AK",
        // etc...
        "WYOMING"=>"WY"
    );

    foreach ($stateArray as $stateName => $stateAbbreviation){
        print "The abbreviation for $stateName is $stateAbbreviation.

";
    }
?>

输出(保留键顺序):

The abbreviation for ALABAMA is AL.

The abbreviation for ALASKA is AK.

The abbreviation for WYOMING is WY.

请注意,数组元素的顺序保留在 php 版本的输出中.使用 HashMap 的 Java 实现不保证元素的顺序.Python 中的字典也没有.

Note that the order of array elements is preserved in the output of the php version. The Java implementation, using a HashMap, does not guarantee the order of elements. Nor does the dictionary in Python.

在java和python中这是如何完成的?我只找到提供值的方法,给定密钥,如 python 的:

How is this done in java and python? I only find approaches that supply the value, given the key, like python's:

stateDict = {
    "ALASKA": "AK",
    "WYOMING": "WY",
}

for key in stateDict:
    value = stateDict[key]

<小时>

根据答案,这是我在 python 中的解决方案,


based on the answers, this was my solution in python,

# a list of two-tuples
stateList = [
    ('ALABAMA', 'AL'),
    ('ALASKA', 'AK'),
    ('WISCONSIN', 'WI'),
    ('WYOMING', 'WY'),
]

for name, abbreviation in stateList:
    print name, abbreviation

输出:

ALABAMA AL
ALASKA AK
WISCONSIN WI
WYOMING WY

这正是所需要的.

推荐答案

在 Python 中:

in Python:

for key, value in stateDict.items(): # .iteritems() in Python 2.x
    print "The abbreviation for %s is %s." % (key, value)

在 Java 中:

Map<String,String> stateDict;

for (Map.Entry<String,String> e : stateDict.entrySet())
    System.out.println("The abbreviation for " + e.getKey() + " is " + e.getValue() + ".");

这篇关于java和python等价于php的foreach($array as $key => $value)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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