如何用特定条件替换列表项的值?

时间:2018-07-16 19:20:05

标签: list replace dart flutter

示例:列表列表=

[ 
    [4, 175.52, 00, 175.52, 175.52], 
    [3, 175.52, 01, 175.52, 175.52]
]
  • 1 = A
  • 2 = B
  • 3 = C
  • 4 = D

还有

  • 00 = AA
  • 01 = BB
  • 12 = CC
  • 15 = DD

我知道我可以在第一项中使用for循环和替换示例,例如: 4到D,00到AA

预期结果:

[ 
    [D, 175.52, AA, 175.52, 175.52], 
    [C, 175.52, BB, 175.52, 175.52]
]

那么,如何用特定条件替换列表项的值?

2 个答案:

答案 0 :(得分:0)

这是一个很奇怪的问题,所以我不确定这是否是您要寻找的东西:

void main() {

  List<List<num>> bigList = [
    [4, 175.52, 00, 175.52, 175.52],
    [3, 175.52, 01, 175.52, 175.52]
  ];

  List<List<dynamic>> newBigList = [];

  for (List<num> smallList in bigList) {
    List<dynamic> newSmallList = [];
    for (num number in smallList) {

      switch (number) {
        case 1:
          newSmallList.add("A");
          break;
        case 2:
          newSmallList.add("B");
          break;
        case 3:
          newSmallList.add("C");
          break;
        case 4:
          newSmallList.add("D");
          break;

        case 00:
          newSmallList.add("AA");
          break;
        case 01:
          newSmallList.add("BB");
          break;
        case 12:
          newSmallList.add("CC");
          break;
        case 15:
          newSmallList.add("DD");
          break;

        default: 
          newSmallList.add(number);
      }
    }

    newBigList.add(newSmallList);
  }

  print(newBigList);
}

此打印:

[[D, 175.52, AA, 175.52, 175.52], [C, 175.52, A, 175.52, 175.52]]

答案 1 :(得分:0)

我的问题是替换此列表中的第一个(item(0))和第三个(item(2))。 [4、175.52、00、175.52、175.52]。上面的帖子@mans给了我正确的答案。区别在于,在他的解决方案中,如果满足特定条件,则可以替换列表中的每个项目。在我的问题是类似的,但仅替换2个项目。我在切换条件之前使用if else语句来获取所需的内容。

void main() {
  List<List<dynamic>> bigList = [
    [2, 175.52, 00, 175.52, 175.52],
    [3, 175.52, 01, 175.52, 175.52]
  ];

  List<List<dynamic>> newBigList = [];

  for (List<dynamic> smallList in bigList) {
    List<dynamic> newSmallList = [];
    for (var number in smallList) {
      if (number == smallList[0]) {
        switch (number) {
          case 1:
            newSmallList.add("A");
            break;
          case 2:
            newSmallList.add("B");
            break;
          case 3:
            newSmallList.add("C");
            break;
          case 4:
            newSmallList.add("D");
            break;

          default:
            newSmallList.add(number);
        }
      } else if (number == smallList[2]) {
        switch (number) {
          case 00:
            newSmallList.add("AA");
            break;
          case 01:
            newSmallList.add("BB");
            break;
          case 12:
            newSmallList.add("CC");
            break;
          case 15:
            newSmallList.add("DD");
            break;
          default:
            newSmallList.add(number);
        }
      } else {
        newSmallList.add(number);
      }

      // if else
    } // inner for
    newBigList.add(newSmallList);
  } // outer for
  print(newBigList);
}