Home > Software engineering >  Iterating over a list of integers and joining items based on a condition
Iterating over a list of integers and joining items based on a condition

Time:11-23

I am attempting to iterate over a list of integers and to join them based on a condition using the python standard library. For example, I have a list of integers that looks as such:

listOfIntegers = [0, 0, 0, 2, 0, 4, 6, 0, 8, 0, 0, 0, 1, 9]

I would like to iterate through this list and combine values such that the result would be a string of the form:

result = '000-20-4-60-8000-1-9'

(where the dashes are included). The condition for this is that if the preceding number is not equal to zero a dash must be placed in front of it. If the next value is equal to zero it is joined to the end of the value before it.

CodePudding user response:

This would help: (Considering numbers are positive in the given list)

def join(lst):
    return "".join(list(map(lambda x: str(-x), lst))).lstrip('-')

listOfIntegers = [0, 0, 0, 2, 0, 4, 6, 0, 8, 0, 0, 0, 1, 9]
print(join(listOfIntegers)) # 000-20-4-60-8000-1-9

The process:

  1. Convert each element to negative, in which:
    • 9 becomes -9
    • 0 has no effect as -0 is 0 in python
  2. Then convert them into strings and join them
  3. Make sure to remove Trailing hyphen, in our case lstrip('-') helps us with that.

CodePudding user response:

A straightforward approach, building a string from the list of integers, followed by a simple regex replacement:

listOfIntegers = [1, 0, 0, 2, 0, 4, 6, 0, 8, 0, 0, 0, 1, 9]
inp = ''.join([str(x) for x in listOfIntegers])
result = re.sub(r'(?<=.)(?=[^\D0])', '-', inp)
print(result)  # 100-20-4-60-8000-1-9

CodePudding user response:

Here is a simple solution:

listOfIntegers = [0, 0, 0, 2, 0, 4, 6, 0, 8, 0, 0, 0, 1, 9]

for i in listOfIntegers:
    if i != 0:
        print("-"   str(i), end="")
    else:
        print(str(i), end="")

For each item in the list, we check if the item is not equal to 0. If it isn't equal to 0, we print out the item with a dash in front of it, and use the end parameter to avoid new lines. If it is 0, we simply print out the item.

CodePudding user response:

Using a loop:

def func(nums):
    result = ''
    for num in nums:
        if num != 0:
            result  = '-'
        result  = str(num)
    return result
  • Related