簡體   English   中英

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

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

在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

這正是所需要的。

在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中為關聯數組使用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()
            );
        }
    }
}

此外,要維護插入順序,可以使用LinkedHashMap而不是HashMap。

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

這是來自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()
            );
      }
    }
 }

在Java中使用它的另一種方法。 雖然已經發布了一種更好的方法,但這個方法在語法上更接近你的php代碼。

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

按照亞歷山大的回答......

本機python字典不維護其主要用途的最大效率的排序:鍵到值的無序映射。

我可以想到兩個解決方法:

  1. 查看OrderedDict的源代碼並將其包含在您自己的程序中。

  2. 制作一個按順序保存按鍵的列表:

     states = ['Alabamba', 'Alaska', ...] statesd = {'Alabamba':'AL', 'Alaska':'AK', ...} for k in states: print "The abbreviation for %s is %s." % (k, statesd[k]) 

TreeMap不是您問題的答案,因為它按鍵對元素進行排序,而LinkedHashMap保留原始順序。 但是,由於排序,TreeMap更適合字典。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM