Python中的Java接口+lambda

2024-09-27 07:35:07 发布

您现在位置:Python中文网/ 问答频道 /正文

给出以下用Java编写的代码片段,有没有一种方法可以优雅地用Python实现相同的结果

班级:

public class SomeClass {

  public static void main(String[] args) {

    ArrayList<String> list = new ArrayList<>();
    list.add("One");
    list.add("Two");
    list.add("Three");

    goOverList(list.size(), (index) -> list.add(String.valueOf(index + 1)));

    list.forEach(System.out::println);
  }

  public static void goOverList(int listSize, Fun fun) {

    for (int i = 0; i < listSize; i++) {
      fun.doStuff(i);
    }

  }
}

接口:

public interface Fun {

  void doStuff(int index);

}

输出:

One
Two
Three
1
2
3

其思想是将任何函数作为参数传递,并获取要使用的索引


Tags: addstringindexstaticpubliconelistint
1条回答
网友
1楼 · 发布于 2024-09-27 07:35:07

5行Python:

the_list = ["One", "Two", "Three"]
for i in range(len(the_list)) :
    the_list.append(str(i + 1))
#end for
print(the_list)

输出:

['One', 'Two', 'Three', '1', '2', '3']

我能赢什么

相关问题 更多 >

    热门问题