一尘不染

java和python等效于php的foreach($ array as $ key => $ value)

python

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

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

    foreach ($stateArray as $stateName => $stateAbbreviation){
        print "The abbreviation for $stateName is $stateAbbreviation.\n\n";
    }
?>

输出(保留键顺序):

The abbreviation for ALABAMA is AL.

The abbreviation for ALASKA is AK.

The abbreviation for WYOMING is WY.

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

如何在Java和python中完成?我只找到给定键的提供值的方法,例如python的方法:

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

for key in stateDict:
    value = stateDict[key]

编辑:基于答案,这是我在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

这正是所需要的。


阅读 225

收藏
2021-01-20

共1个答案

一尘不染

在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() + ".");
2021-01-20