Joining elements in a list without the join comman

2019-01-07 00:04发布

问题:

I need to join the elements in a list without using the join command, so if for example I have the list:

[12,4,15,11]

The output should be:

1241511

Here is my code so far:

def lists(list1):
    answer = 0
    h = len(list1)
    while list1 != []:
        answer = answer + list1[0] * 10 ** h
        h = h - 1
        list1.pop(0)
    print(answer)

But, in the end, the answer ends up being 125610 which is clearly wrong.

I think the logic is OK, but I can't find the problem?

回答1:

If you just want to print the number rather than return an actual int:

>>> a = [12,4,15,11]
>>> print(*a, sep='')
1241511


回答2:

You could just convert each element to a string, add them, and then convert back to an int:

def lists(list1):
    answer=''
    for number in list1:
        answer+=str(number)
    print(int(answer))


lists([12,4,15,11])

>>> 
1241511


回答3:

s = ""
for x in map(str, x):
    s += x

print(s)
1241511


回答4:

There can be few more options like

Option1

>>> lst=[12,4,15,11]
>>> str(lst).translate(None, '[,] ')
'1241511'

Option 2

>>> join = lambda e: str(e[0]) + join(e[1:]) if e else ""
>>> join(lst)
'1241511'

Option 3

>>> ("{}"*len(lst)).format(*lst)
'1241511'

Option 4

>>> reduce(lambda a,b:a+b,map(str,lst))
'1241511'


回答5:

a numeric solution, using your code

import math

def numdig(n):
  #only positive numbers
  if n > 0:
    return int(math.log10(n))+1
  else:
    return 1

def lists(list1):
  answer = 0
  h = 0
  while list1 != []:
    answer = answer * 10 ** h + list1[0]
    list1.pop(0)
    if list1 != []:
      h = numdig(list1[0])
  print(answer)

lists([12,4,15,11])


回答6:

You may try map and reduce with lambda like this:

def without_join(alist):
  try:
    return int(reduce(lambda a,b: a + b, map(str, alist)))
  except ValueError, error:
    print error

  return None


print without_join([12,4,15,11])


回答7:

Here's an entirely numerical solution, playing off of your notion of messing with powers of 10. You were on the right track, but your implementation assumed all values were 1 digit long.

import math

def lists(list1):
    b = 0
    foo = 0
    for item in reversed(list1):
        b += item*(10**foo)
        foo += int(math.floor(math.log10(item))) + 1
    return b

a = [12, 4, 15, 11]
print lists(a)

This returns 1241511, as requested.

All I'm doing here is looping through the list in reverse order and keeping track of how many digits to the left I need to shift each value. This allows integers with an arbitrary number of digits.



标签: python list join