如何循环遍历一个列表的列表,以便操作内部列表的内容?

huangapple go评论77阅读模式
英文:

How do I loop through a list of lists in order to manipulate the contents of the inner lists?

问题

我想循环遍历一个列表的列表,并访问内部列表项,以便有条件地向列表中添加项目。我想象中的代码大致如下:

for 每个子列表 in 主列表:
    如果 子列表[4] = "x" 并且 子列表[5] = "y",
        子列表.添加("z")

我在添加到列表或比较字符串方面没有问题,只是不知道如何从循环遍历主列表转到检查子列表中的项目。

英文:

I'd like to loop through a list of lists and access the inner-list items in order to append an item to the list conditionally. I'm imagining something along the lines of

 for each sublist in mainlist, 
     if sublist[4] = "x" and sublist[5] = "y", 
       sublist.add("z")

I have no issue adding to the list or comparing the strings, I just don't know how to get from looping through the main list to checking the item's in the sublists.

答案1

得分: 0

以下是一个非常简单的示例,用于在Java中循环遍历一个列表的列表:

import java.util.ArrayList;
import java.util.List;

public class Main {
    
    public static void main(String[] args) {
        
        List<ArrayList<String>> mainList = new ArrayList<ArrayList<String>>();
        
        ArrayList<String> subList1 = new ArrayList<String>();
        subList1.add("A");
        subList1.add("B");
        
        mainList.add(subList1);
 
        ArrayList<String> subList2 = new ArrayList<String>();
 
        subList2.add("C");
        subList2.add("D");
        mainList.add(subList2);
        
        for (int i = 0; i < mainList.size(); i++) { 
            for (int j = 0; j < mainList.get(i).size(); j++) { 
                System.out.print(mainList.get(i).get(j) + " "); 
            } 
            System.out.println(); 
        } 
        
        // Using for each
        System.out.println("Using for-each");
        mainList.forEach((list) -> {list.forEach((alphabet)->System.out.println(alphabet)); });
    }
}

输出示例:

A B                                                                                                                                                        
C D   
                                                                                                                                                     
Using for-each                                                                                                                                             
A                                                                                                                                                          
B                                                                                                                                                          
C                                                                                                                                                          
D

现在您可以放置您想要的条件。
英文:

Here is a very simple example to loop through a List of lists in Java :

import java.util.ArrayList;
import java.util.List;

public class Main {
    
	public static void main(String[] args) {
	    
		List&lt;ArrayList&lt;String&gt;&gt; mainList = new ArrayList&lt;ArrayList&lt;String&gt;&gt;();
		
		ArrayList&lt;String&gt; subList1 = new ArrayList&lt;String&gt;();
		subList1.add(&quot;A&quot;);
		subList1.add(&quot;B&quot;);
		
		mainList.add(subList1);
 
		ArrayList&lt;String&gt; subList2 = new ArrayList&lt;String&gt;();
 
		subList2.add(&quot;C&quot;);
		subList2.add(&quot;D&quot;);
		mainList.add(subList2);
		
		for (int i = 0; i &lt; mainList.size(); i++) { 
            for (int j = 0; j &lt; mainList.get(i).size(); j++) { 
                System.out.print(mainList.get(i).get(j) + &quot; &quot;); 
            } 
            System.out.println(); 
        } 
        
        // Using for each
        System.out.println(&quot;Using for-each&quot;);
		mainList.forEach((list)  -&gt; {list.forEach((alphabet)-&gt;System.out.println(alphabet)); });
	}
}

Sample Output :

A B                                                                                                                                                        
C D   
                                                                                                                                                 
Using for-each                                                                                                                                             
A                                                                                                                                                          
B                                                                                                                                                          
C                                                                                                                                                          
D

Now you can place your desired conditions.

答案2

得分: 0

根据问题中发布的代码,它正按照所需方式进行操作。mainlist是一个列表的列表,sublist是字符串的列表,在子列表中添加z会更新主列表,因为您是在引用上进行更新。

这个Java版本可能是:

for (List<String> subList : mainList) {
  if (null != sublist && !sublist.isEmpty() && sublist.get(4).equals("x") &&
      sublist.get(5).equals("y")) {
    sublist.add("z");
  }
}
英文:

As per the code posted in question, it is exactly doing what is required. The mainlist being a list of lists, sublist being a list of strings, adding z to the sublist updates it in the main list since you are updating on the reference.

The java version for this could be:

for (List &lt;String&gt; subList: mainList) {
  if (null != sublist &amp;&amp; !sublist.isEmpty() &amp;&amp; sublist.get(4).equals(&quot;x&quot;) &amp;&amp;
    sublist.get(5).equals(&quot;y&quot;)) {
    sublist.add(&quot;z&quot;);
  }
}

答案3

得分: 0

请尝试以下方式:

public static void main(String[] args) {

    List<List<String>> parentList = new ArrayList();

    List<String> listA = new ArrayList<String>();
    listA.add("listA-item1");
    listA.add("listA-item2");
    listA.add("listA-item3");

    List<String> listB = new ArrayList<String>();
    listB.add("listB-item1");
    listB.add("listB-item2");
    listB.add("listB-item3");

    parentList.add(listA);
    parentList.add(listB);

    for (List<String> list : new ArrayList<>(parentList)) {

        for (String s : new ArrayList<>(list)) {
            list.remove(s);
            s += " appended thing";
            list.add(s);
        }
    }

    listA.forEach(System.out::println);
    listB.forEach(System.out::println);

}

输出结果为:

listA-item1 appended thing
listA-item2 appended thing
listA-item3 appended thing
listB-item1 appended thing
listB-item2 appended thing
listB-item3 appended thing

请注意,在foreach语句中我创建了新的ArrayList:

for (List<String> list : new ArrayList<>(parentList)) {

    for (String s : new ArrayList<>(list)) {

如果不这样做,会出现java.util.ConcurrentModificationException异常。

英文:

Try this way:

public static void main(String[] args) {

        List&lt;List&lt;String&gt;&gt; parentList = new ArrayList();

        List&lt;String&gt; listA = new ArrayList&lt;String&gt;();
        listA.add(&quot;listA-item1&quot;);
        listA.add(&quot;listA-item2&quot;);
        listA.add(&quot;listA-item3&quot;);

        List&lt;String&gt; listB = new ArrayList&lt;String&gt;();
        listB.add(&quot;listB-item1&quot;);
        listB.add(&quot;listB-item2&quot;);
        listB.add(&quot;listB-item3&quot;);

        parentList.add(listA);
        parentList.add(listB);

        for (List&lt;String&gt; list : new ArrayList&lt;&gt;(parentList)) {

            for (String s : new ArrayList&lt;&gt;(list)) {
                list.remove(s);
                s += &quot; appended thing&quot;;
                list.add(s);
            }
        }

        listA.forEach(System.out::println);
        listB.forEach(System.out::println);

    }

and the output is :

listA-item1 appended thing
listA-item2 appended thing
listA-item3 appended thing
listB-item1 appended thing
listB-item2 appended thing
listB-item3 appended thing

Just take attention to the fact that I am creating new ArralyList in foreach statement :

for (List&lt;String&gt; list : new ArrayList&lt;&gt;(parentList)) {

            for (String s : new ArrayList&lt;&gt;(list)) {

if you do not do that you will get java.util.ConcurrentModificationException

huangapple
  • 本文由 发表于 2020年7月27日 22:42:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/63117719.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定