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

发布于 2024-07-30 03:18:12 字数 1208 浏览 4 评论 0原文

在 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

这正是所需要的。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

尘世孤行 2024-08-06 03:18:12

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

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() + ".");
遗弃M 2024-08-06 03:18:12

在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()
            );
        }
    }
}

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()
            );
        }
    }
}
夏尔 2024-08-06 03:18:12

此外,为了保持插入顺序,您可以使用 LinkedHashMap 而不是 HashMap。

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

ゝ偶尔ゞ 2024-08-06 03:18:12

在Python中,有序字典在Python 2.7中可用(尚未发布)和Python 3.1。 它被称为 OrderedDict。

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

画中仙 2024-08-06 03:18:12

这是来自 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()
            );
      }
    }
 }

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.

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()
            );
      }
    }
 }
万人眼中万个我 2024-08-06 03:18:12

Java 中的另一种方法。 尽管已经发布了更好的方法,但这个方法在语法上更接近您的 php 代码。

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

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));
    }
紅太極 2024-08-06 03:18:12

沿着亚历山大的回答......

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

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

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

  2. 创建一个按顺序保存键的列表:

    states = ['阿拉巴巴', '阿拉斯加', ...]   
      statesd = {'阿拉巴巴':'AL', '阿拉斯加':'AK', ...} 
      对于状态中的 k: 
          print "%s 的缩写是 %s。"   % (k, 表示d[k]) 
      

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])
    
云柯 2024-08-06 03:18:12

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文