So the goal of this code is to print as many permutations as possible from a list of words in a text file. I save all these permutations as a list within a larger list. I am trying to loop through the larger list and print each smaller list as a string.
For example if we have after parsing the input file: [("hi", "bye", "tree"), ("bye", "hi", "tree")]
I want to print this out as:
hibyetree
byehitree
The code I currently have is: click here for code
but this returns:
hi
bye
tree
bye
hi
tree
Just use parameter end
of function print()
print(something,end="")
the prints everything in the list,
list = [("hi", "bye", "tree"), ("bye", "hi", "tree")]
for ind, elem in enumerate(list):
for j in range(len(list[ind])):
print(elem[j])
result:
hi bye tree bye hi tree
lst = [("hi", "bye", "tree"), ("bye", "hi", "tree")]
print(*(''.join(item) for item in lst), sep='\n')
''.join()
joins the given items, in your case, the elements of the passed tuples with the empty string ''
, effectively concatenating them.
*(''.join(item) for item in lst)
runs all of this for each item of the outer list. Each item
is one of said tuples. The parentheses mean, that this is a generator expression, which is immediately unpacked with the asterisk *
. This means that each of the resulting elements will be passed as a positional argument to print()
.
Each of those items are printed, separated by the string specified by the keyword argument sep
, which defaults to ' '
, ie space. Since you want all of it on a separate line, we use the newline character '\n'
instead.
An equivalent functional alternative using the built-in map()
would be:
lst = [("hi", "bye", "tree"), ("bye", "hi", "tree")]
print(*map(''.join, lst), sep='\n')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.