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

时间:2021-08-26 22:09:00

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

在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";
    }
?>

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.

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

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

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

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

for key in stateDict:
    value = stateDict[key]

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

编辑:根据答案,这是我在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 个解决方案

#1


32  

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() + ".");

#2


6  

in java for associative array use Map

在java中为关联数组使用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


2  

Also, to maintain insertion order, you can use a LinkedHashMap instead of a HashMap.

此外,要维护插入顺序,可以使用LinkedHashMap而不是HashMap。

#4


2  

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

在python中,Python 2.7(尚未发布)和Python 3.1中提供了有序字典。它被称为OrderedDict。

#5


2  

This is the modified code from o948 where you use a TreeMap instead of a HashMap. The Tree map will preserve the ordering of the keys by the key.

这是来自o948的修改代码,您使用TreeMap而不是HashMap。树映射将通过键保留键的顺序。

import java.util.*;

class Foo
{
 public static void main(String[] args)
 {
    Map<String, String> stateMap = new TreeMap<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()
            );
      }
    }
 }

#6


1  

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

在Java中使用它的另一种方法。虽然已经发布了一种更好的方法,但这个方法在语法上更接近你的php代码。

for (String x:stateDict.keySet()){
        System.out.printf("The abbreviation for %s is %s\n",x,stateDict.get(x));
    }

#7


1  

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.

本机python字典不维护其主要用途的最大效率的排序:键到值的无序映射。

I can think of two workarounds:

我可以想到两个解决方法:

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

    查看OrderedDict的源代码并将其包含在您自己的程序中。

  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])
    

#8


0  

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.

TreeMap不是您问题的答案,因为它按键对元素进行排序,而LinkedHashMap保留原始顺序。但是,由于排序,TreeMap更适合字典。

#1


32  

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() + ".");

#2


6  

in java for associative array use Map

在java中为关联数组使用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


2  

Also, to maintain insertion order, you can use a LinkedHashMap instead of a HashMap.

此外,要维护插入顺序,可以使用LinkedHashMap而不是HashMap。

#4


2  

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

在python中,Python 2.7(尚未发布)和Python 3.1中提供了有序字典。它被称为OrderedDict。

#5


2  

This is the modified code from o948 where you use a TreeMap instead of a HashMap. The Tree map will preserve the ordering of the keys by the key.

这是来自o948的修改代码,您使用TreeMap而不是HashMap。树映射将通过键保留键的顺序。

import java.util.*;

class Foo
{
 public static void main(String[] args)
 {
    Map<String, String> stateMap = new TreeMap<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()
            );
      }
    }
 }

#6


1  

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

在Java中使用它的另一种方法。虽然已经发布了一种更好的方法,但这个方法在语法上更接近你的php代码。

for (String x:stateDict.keySet()){
        System.out.printf("The abbreviation for %s is %s\n",x,stateDict.get(x));
    }

#7


1  

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.

本机python字典不维护其主要用途的最大效率的排序:键到值的无序映射。

I can think of two workarounds:

我可以想到两个解决方法:

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

    查看OrderedDict的源代码并将其包含在您自己的程序中。

  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])
    

#8


0  

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.

TreeMap不是您问题的答案,因为它按键对元素进行排序,而LinkedHashMap保留原始顺序。但是,由于排序,TreeMap更适合字典。