java and python equivalent of php's foreach($a

2020-02-13 07:22发布

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.\n\n";
    }
?>

Output (with key order preserved):

The abbreviation for ALABAMA is AL.

The abbreviation for ALASKA is AK.

The abbreviation for WYOMING is WY.

EDIT: 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.

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]

EDIT: 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

Output:

ALABAMA AL
ALASKA AK
WISCONSIN WI
WYOMING WY

Which is exactly what was required.

8条回答
我只想做你的唯一
2楼-- · 2020-02-13 07:56

in java for associative array use Map

import java.util.*;

class Foo
{
    public static void main(String[] args)
    {
        Map<String, String> stateMap = new HashMap<String, String>();
        stateMap.put("ALABAMA", "AL");
        stateMap.put("ALASKA", "AK");
        // ...
        stateMap.put("WYOMING", "WY");

        for (Map.Entry<String, String> state : stateMap.entrySet()) {
             System.out.printf(
                "The abbreviation for %s is %s%n",
                state.getKey(),
                state.getValue()
            );
        }
    }
}
查看更多
爷的心禁止访问
3楼-- · 2020-02-13 07:57

Along the lines of Alexander's answer...

The native python dictionary doesn't maintain ordering for maximum efficiency of its primary use: an unordered mapping of keys to values.

I can think of two workarounds:

  1. look at the source code of OrderedDict and include it in your own program.

  2. make a list that holds the keys in order:

    states = ['Alabamba', 'Alaska', ...]  
    statesd = {'Alabamba':'AL', 'Alaska':'AK', ...}
    for k in states:
        print "The abbreviation for %s is %s." % (k, statesd[k])
    
查看更多
放我归山
4楼-- · 2020-02-13 07:59

in Python:

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

in Java:

Map<String,String> stateDict;

for (Map.Entry<String,String> e : stateDict.entrySet())
    System.out.println("The abbreviation for " + e.getKey() + " is " + e.getValue() + ".");
查看更多
放荡不羁爱自由
5楼-- · 2020-02-13 08:03

In python an ordered dictionary is available in Python 2.7 (not yet released) and Python 3.1. It's called OrderedDict.

查看更多
放荡不羁爱自由
6楼-- · 2020-02-13 08:03

Another way of doing it in Java. Although a better way has already been posted, this one's syntactically closer to your php code.

for (String x:stateDict.keySet()){
        System.out.printf("The abbreviation for %s is %s\n",x,stateDict.get(x));
    }
查看更多
爱情/是我丢掉的垃圾
7楼-- · 2020-02-13 08:05

TreeMap is not an answer to your question because it sorts elements by key, while LinkedHashMap preserves original order. However, TreeMap is more suitable for the dictionary because of sorting.

查看更多
登录 后发表回答