我最近学会了使用ìtemgetter(i)在python中获取多个列表中的ith元素。例如:
j_column=list(map(itemgetter(j), board[i+1:]))board[i+1]部件返回一个列表列表,每个列表表示第一行下的水平行、董事会的一个子部分,上面的代码返回该小节的jth列。
现在,我在做类似的事情,在一个列表中,我必须获得n个列表的ith元素。我不知道,但我必须用Java来完成这个任务。我现在正在寻找与itemgetter(i)函数等价的东西,但是在Java中
更多信息:
假设我有一个列表,例如:my_list将输出[[1,4,5,6,7],[3,0,0,9,8,4],[1,4,5]],并且我所寻找的函数称为someFunction,并且我希望每个子列表中有第三个数字,这意味着每个子列表中索引2处的每个元素,这就是我要寻找的:
somefunction(2, my_list); //this would output [5,0,5]发布于 2017-05-16 19:52:32
正如您在评论中所指出的,您
List<List<Something>>ith元素,将其添加到新的List<Something>并返回该列表。这一守则应该足够:
/**
* Method is parameterized in the list-type, thus achieving maximal type checking. If the
* inner lists are of different types, the inner lists must be of type List<Object>,
* other types will not work. Type-checking is out of the window at that point.
*
* @param lists the list of lists, non-null and not containing null's.
* @param i the index to pick in each list, must be >= 0.
* @param <T> generic parameter of inner lists, see above.
* @return a List<T>, containing the picked elements.
*/
public static <T> List<T> getIthOfEach(List<List<T>> lists, int i) {
List<T> result = new ArrayList<T>();
for(List<T> list : lists) {
try {
result.add(list.get(i)); // get ith element, add it to the result-list
// if some list does not have an ith element, an IndexOutOfBoundException is
// thrown. Catch it and continue.
} catch (IndexOutOfBoundsException e) { }
}
return (result);
}您可以这样调用此方法:
List<Integer> everyFifthInteger = getIthOfEach(listOfListsOfIntegers, 5);
List<Object> everyFifthThing = getIthOfEach(listOfListsOfthings, 5);发布于 2017-05-16 20:04:24
我在Java中使用高级函数的经验是相当有限的(坦率地说,从Python转换是有点痛苦的),但这类似于Python中的itemgetter,虽然它只接受单个参数,而itemgetter在Python中使用可变数量的参数,但是如果您真的需要它,您可以自己实现它(尽管,我不确定应该返回哪种容器类型,Python使用元组,我不知道在Java中会有什么好的替代品):
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.function.Function;
class Main {
public static <T> List<T> asList(T ... items) {
List<T> list = new ArrayList<T>();
for (T item : items) {
list.add(item);
}
return list;
}
public static <T> Function<List<T>, T> itemgetter(int i){
Function<List<T>, T> f = l -> l.get(i);
return f;
}
public static void main(String[] args) {
List<List<Integer>> myList = asList(
asList(1,4,5,6,7),
asList(3,0,0,9,8,4),
asList(1,4,5)
);
List newList = myList.stream()
.map(itemgetter(2))
.collect(Collectors.toList());
System.out.println(newList);
}
}以及产出:
[5, 0, 5]https://stackoverflow.com/questions/44009818
复制相似问题