To join a python list element to a certain rule

Asked 2 years ago, Updated 2 years ago, 84 views

# Parsing match
alpha_list = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P"]

# After parsing 
alpha_list = ["A", "&", "B", "&", "C", "&", "D", "&&", "E", "&", "F", "&", "G", "&", "H", "&&", "I", "&", "J", "&", "K", "&", "L", "&&", "M", "&", "N", "&", "O", "&", "P"]

Like the list above, a list containing alphabetic strings from A to P I want to add "&" between elements and change the list to "&&" instead of "&" every fourth element.
However, the last element must not be & or &&.

python join for loops while-loop

2022-09-20 19:35

2 Answers

>>> l2
['A', '&', 'B', '&', 'C', '&', 'D', '&&']
>>> l2 = l2[:-1]
>>> l2
['A', '&', 'B', '&', 'C', '&', 'D']

Don't think too hard. It's a good enough solution to add i%4 based on the conditions.

Something useless came out at the end You only need to remove the last one. Stupidly easy code is a good code.


2022-09-20 19:35

val alpha_list = Seq("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P")

def makeString(s: Seq[String]): Seq[String] = {
    @annotation.tailrec
    def _execute(s: Seq[String], acc: Seq[String] = Seq.empty, i: Int = 1): Seq[String] = s match {
        case Nil => acc.dropRight(1)
        case x :: xs => _execute(xs, acc ++ (if(i % 4 == 0) Seq(x, "&&") else Seq(x, "&")), i + 1)
    }
    _execute(s)
}

makeString(alpha_list)
=> Seq[String] = List(A, &, B, &, C, &, D, &&, E, &, F, &, G, &, H, &&, I, &, J, &, K, &, L, &&, M, &, N, &, O, &, P)


2022-09-20 19:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.