-1

I've got multiple lists (list1, list2, ...) which depends on a number of elements (they may change) in another listX -> len(listX)

How to append all of these lists of strings into one string followed by ";"?

list1 = ['a', 'b'] list2 = ['c', 'd'] ... listn = ['x', 'y']

the final string should look like: 'a;b;c;d;...;x;y'

Sebastian
  • 31
  • 6

1 Answers1

1

Well, how about collecting all the individual lists into a single list and then joining the individual items together.

Approach 1:- Collecting all the list and then joining them

intermidiate_list = list()
for i in range(len(mega_list)):
    intermidiate_list.extend(mega_list(i))

result = ";".join(intermidiate_list)

Here mega_list is the collection of all the lists you have. You can iterate over them by indexes and still make it work.

Approach 2:- Generating the list on the fly

result = str()
small_list = get_list()
while small_list:
    result += ";".join(small_list)
    small_list = get_list()
    if small_list and len(small_list) > 0:
        result += ";"

Now iterate the logic for all the list items you generate, in the end result will have the

onlinejudge95
  • 333
  • 3
  • 9
  • not always I know how many lists I have and they are named list_1, list_2, list_n .. the question is how to loop for these lists – Sebastian Feb 22 '20 at 14:56
  • i tried something like: for i in range(len(listX)): list_of_all.append(wordListDE+str(i)). but does not work @onlinejudge95 – Sebastian Feb 22 '20 at 14:58
  • thanks, but how can i create this mega_list? @onlinejudge95 – Sebastian Feb 22 '20 at 15:14
  • may I know in what way do you have the individual lists? Do you know beforehand how many of them are there? – onlinejudge95 Feb 22 '20 at 15:17
  • it is webscraping and these lists of items depend on how many themes are present on a specific date, that is why the number is different and if len(theme) = 6 then I have six lists of items – Sebastian Feb 22 '20 at 15:20
  • So while scraping you can append these lists into the `mega_list`, and once scraping is complete then go around with the above logic – onlinejudge95 Feb 22 '20 at 15:21
  • no, these lists don't correspond to anything with web scraping; it is my own input there – Sebastian Feb 22 '20 at 15:22
  • Simply put, create an empty `mega_list`, now whenever you get a single list just append it to the `mega_list` once you have all the items collected, then apply the join logic – onlinejudge95 Feb 22 '20 at 15:24
  • the thing is that I would like to get it with loop by list index so that I dont append each of them manually – Sebastian Feb 22 '20 at 15:25