3

I need to take a list, multiply every item by 4 and separate them by coma.

My code is:

conc = ['0.05 ml : 25 ml', '0.05 ml : 37.5 ml', '0.05 ml : 50 ml', '0.05 ml : 62.5 ml', '0.05 ml : 75 ml']
new_conc = [", ".join(i*4) for i in conc]
print(new_conc)

But when I run it, I get every SYMBOL separated by come. What I need is multiplied number of shown EXPRESSIONS separated by coma.

So the output should be:

['0.05 ml : 25 ml', '0.05 ml : 25 ml', '0.05 ml : 25 ml', '0.05 ml : 25 ml', '0.05 ml : 37.5 ml', '0.05 ml : 37.5 ml', '0.05 ml : 37.5 ml', '0.05 ml : 37.5 ml', '0.05 ml : 50 ml', '0.05 ml : 50 ml', '0.05 ml : 50 ml', '0.05 ml : 50 ml', '0.05 ml : 62.5 ml', '0.05 ml : 62.5 ml', '0.05 ml : 62.5 ml', '0.05 ml : 62.5 ml', '0.05 ml : 75 ml', '0.05 ml : 75 ml', '0.05 ml : 75 ml', '0.05 ml : 75 ml']

I found this answered question, but as I already mentioned, I get separate symbols, separated by coma.

  • Your list contains strings, not numbers. When you use `*` on a string, it duplicates it that many times. – Barmar Feb 23 '23 at 21:55

4 Answers4

3

You can use a simple for loop.

new_conc = []
for item in conc:
    new_conc.extend([item] * 4)
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thank you! Can you also please look at [this](https://stackoverflow.com/questions/75549047/making-a-3d-graph-from-the-csv-file-problem-looping-over-csv-file) question? – PythonLover Feb 23 '23 at 22:09
1

You can try double for-loop:

conc = ['0.05 ml : 25 ml', '0.05 ml : 37.5 ml', '0.05 ml : 50 ml', '0.05 ml : 62.5 ml', '0.05 ml : 75 ml']

out = []
for item in conc:
    for _ in range(4):
        out.append(item)
print(out)

Or one-liner:

out = [item for item in conc for _ in range(4)]

Or (if order as you stated in your output is not important):

out = conc * 4
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

Welcome to StackOverFlow! As correctly pointed out by other users, you can't directly multiply a string, you need to "separate" the numeric part from the non-numeric one, then you can perform your multiplication, and finally rejoin the numeric and the string parts.

conc = ['0.05 ml : 25 ml', '0.05 ml : 37.5 ml', '0.05 ml : 50 ml', '0.05 ml : 62.5 ml', '0.05 ml : 75 ml']

multiplied_conc = [': '.join([f"{float(p.split()[0])*4} {p.split()[1]}" for p in c.split(' : ')]) for c in conc]

print(multiplied_conc)
shannontesla
  • 885
  • 1
  • 8
  • 27
0

Okay, when I despaired of finding an answer and posted this question, I found this answered question. :)

So the solution to my problem can be:

b = [4, 4, 4, 4]
c = sum([[s] * n for s, n in zip(conc, b)], [])
print(c)

But, if you, guys, know better solution, I will be happy to hear it!

  • You don't need the `b` list if it's always 4. Just use `[s] * 4` – Barmar Feb 23 '23 at 21:57
  • Thank you! I am pretty new to Python and although I spend a lot of time studying it, I still sometimes get confused about simple things :) Thank you! – PythonLover Feb 23 '23 at 22:00