1

I have four lists called items2 ( quantity) , items ( the codes) , newprice_list (final price) and product_list (the name of the products). I tried to print them side-by-side like this:

123213  banana   4   £5

I tried this...

All_list=[items , product_list , newprice_list , items2]
for a in zip(*All_list):
    print(*a)

...however it gave me this output:

86947367 banana
 10 2

The thing is , when I print out the lists newprice_list and items2 they do not have the " quotes like the other two lists , which I think is the problem, however I do not know how to solve it. I have turned items2 and items into integers.

EDIT: When I rearrange the order it works, however I need it to be in that order.

smci
  • 32,567
  • 20
  • 113
  • 146
  • anyone , has an alternative method ? –  Sep 01 '16 at 13:38
  • 1
    Your items list is terminated with newline characters. – L3viathan Sep 01 '16 at 16:54
  • Vaguely related questions on shopping-cart calculations: [Multiplying and then summing values from two dictionaries (prices, stock)](https://stackoverflow.com/questions/16087118/multiplying-and-then-summing-values-from-two-dictionaries-prices-stock). And take a browse of the [tag:shopping-cart] tag. – smci Apr 30 '18 at 08:14
  • Your items list seems to be terminated with newlines, so clean it up by running `items = [i.strip() for i in items]`. See [**How do I trim whitespace?**](https://stackoverflow.com/questions/1185524/how-do-i-trim-whitespace/1185529#1185529) or [Remove all whitespace in a string in Python](https://stackoverflow.com/questions/8270092/remove-all-whitespace-in-a-string-in-python) – smci Apr 30 '18 at 08:16
  • Possible duplicate of [How do I trim whitespace?](https://stackoverflow.com/questions/1185524/how-do-i-trim-whitespace) – smci Apr 30 '18 at 08:18

1 Answers1

0

Instead of print(*a), which is changed to print("382918", "banana", ...), try printing the array a seperating it by spaces:

print(' '.join(list(map(str, a))))
  1. Map applies "str" to each element in a
  2. list changes the type to list (return value is list of strings)
  3. ' '.join(..) generates string where values in list (generated by list(map(...))) are joine by space.

If you have \n that triggers new line somewhere, you can strip it in the same one-liner:

print(' '.join(list(map(lambda x: strip(str(x)), a))))

Lambda is anonimous function that will be applied to each element of a. It turns it to string (not changes if already string) and strips all the \ns

Dmitry Torba
  • 3,004
  • 1
  • 14
  • 24
  • If you're immediately consuming the `map` you don't need to wrap it in a `list`; `' '.join(map(str, a))` is fine, and avoids creating an unnecessary intermediate list. Also, I'd recommend using a comprehension instead of a lambda expression in a map: `' '.join(str(x).strip() for x in a)` – Orez Sep 16 '18 at 06:12