Flutter Dart lang,如何使用组合元素将列表映射到列表?
我有一张单子 最终列表=[1,2,3,4,5,6,7] 如何将输出映射为新列表,如:Flutter Dart lang,如何使用组合元素将列表映射到列表?,flutter,dart,Flutter,Dart,我有一张单子 最终列表=[1,2,3,4,5,6,7] 如何将输出映射为新列表,如: "1 and 2", "3 and 4", "5 and 6", "7" 我脑子里想不出答案,但试试这个: final List list = [1, 2, 3, 4, 5, 6, 7]; List<String> grouped = []; for (int i = 0; i < list.length; i++) { if (i % 2 == 0) { if
"1 and 2",
"3 and 4",
"5 and 6",
"7"
我脑子里想不出答案,但试试这个:
final List list = [1, 2, 3, 4, 5, 6, 7];
List<String> grouped = [];
for (int i = 0; i < list.length; i++) {
if (i % 2 == 0) {
if (i + 1 < list.length) {
grouped.add("${list[i]} and ${list[i + 1]}");
} else {
grouped.add("${list[i]}");
break;
}
}
}
print(grouped);
我脑子里想不出答案,但试试这个:
final List list = [1, 2, 3, 4, 5, 6, 7];
List<String> grouped = [];
for (int i = 0; i < list.length; i++) {
if (i % 2 == 0) {
if (i + 1 < list.length) {
grouped.add("${list[i]} and ${list[i + 1]}");
} else {
grouped.add("${list[i]}");
break;
}
}
}
print(grouped);
这很有效
main(){
final List list = [1,2,3,4,5,6,7];
final List newList = [];
for(int i = 0; i<list.length; i++){
var string;
if(i+1<list.length){
string = "${list[i]} and ${list[i+1]}";
i++;
}else{
string = "${list[i]}";
}
newList.add(string);
}
print(newList);
}
这很有效
main(){
final List list = [1,2,3,4,5,6,7];
final List newList = [];
for(int i = 0; i<list.length; i++){
var string;
if(i+1<list.length){
string = "${list[i]} and ${list[i+1]}";
i++;
}else{
string = "${list[i]}";
}
newList.add(string);
}
print(newList);
}
您可以使用以下功能实现这一点:
_getComponents(list) => list.isEmpty ? list :
([list
.take(2)
.join(' and ')
]..addAll(_getComponents(list.skip(2))));
调用该函数,如下所示:
List outPut = _getComponents(yourList);
说明:
您正在声明一个名为_getComponents的递归函数
作为第一条语句,您将检查参数列表是否为空,如果为空,则按原样返回参数
如果列表不是空的
您正在使用函数从列表中获取前2项
您正在使用函数连接这些元素
您正在调用该函数,并将递归_getComponents调用的结果作为其参数提供
作为_getComponents函数的参数,在跳过使用该函数的前2个元素后,您将传递该列表
您可以使用以下功能实现这一点:
_getComponents(list) => list.isEmpty ? list :
([list
.take(2)
.join(' and ')
]..addAll(_getComponents(list.skip(2))));
调用该函数,如下所示:
List outPut = _getComponents(yourList);
说明:
您正在声明一个名为_getComponents的递归函数
作为第一条语句,您将检查参数列表是否为空,如果为空,则按原样返回参数
如果列表不是空的
您正在使用函数从列表中获取前2项
您正在使用函数连接这些元素
您正在调用该函数,并将递归_getComponents调用的结果作为其参数提供
作为_getComponents函数的参数,在跳过使用该函数的前2个元素后,您将传递该列表
写下:
void main(){
final List oldList = [1,2,3,4,5,6,7];
final List newList = [];
for(int i = 0; i<list.length; i += 2){
if(i+1<oldList.length){
newList.add("${oldList[i]} and ${oldList[i+1]}");
}else{
newList.add("${oldList[i]}");
}
}
print(newList);
}
写下:
void main(){
final List oldList = [1,2,3,4,5,6,7];
final List newList = [];
for(int i = 0; i<list.length; i += 2){
if(i+1<oldList.length){
newList.add("${oldList[i]} and ${oldList[i+1]}");
}else{
newList.add("${oldList[i]}");
}
}
print(newList);
}