1

Input list example = ['listen, silent', 'dog, fog', 'colour, simple']

how do I return a nested list from the example in pairs, to look like this:

[[word1,word2], [word3,word4]...etc]

please, thank you

I have tried list comprehension,

my_list1 = [i[1] for i in my_list]
 my_list2 = [i[0] for i in my_list]

but it took out only the first letter instead of word... hoping for it to look like;

[listen, silent],[dog, fog]...etc
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
Zara
  • 87
  • 7
  • What have you tried so far, @Alice? Please edit your question to detail your tries, otherwise, most probably your question will be closed – Luan Naufal Dec 02 '18 at 15:20
  • but you can try the split method to do so: https://stackoverflow.com/questions/4071396/split-by-comma-and-strip-whitespace-in-python – Luan Naufal Dec 02 '18 at 15:21
  • What is your expected output for your example `['listen, silent', 'dog, fog', 'colour, simple']`? `[['listen, silent'], ['dog, fog'], ['colour, simple']]`? – quant Dec 02 '18 at 15:22
  • @quant yes exactly that – Zara Dec 02 '18 at 15:23

1 Answers1

3

You can split each word in the list using , as a separator:

l = ['listen, silent', 'dog, fog', 'colour, simple']

l = [elem.split(', ') for elem in l]
print(l)

Output:

[['listen', 'silent'], ['dog', 'fog'], ['colour', 'simple']]
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
  • thank you so very much! Much appreciated – Zara Dec 02 '18 at 15:29
  • You're welcome. Is this what you were asking for? Because in your question it is kind of unclear whether you want to split each string and get the two words, or place each string in a list like this: `[['listen, silent'],['dog, fog'], ['colour, simple']]`. Notice the difference between these two. – Vasilis G. Dec 02 '18 at 15:30
  • ah, my next step is to use a sorted function in order to check if the list of words are anagrams or not (so read_anagram: if (sorted(s1)==sorted(s2)) )- therefore the function needs to recognise the pairs into 2 strings.. so perhaps for this, your first output would work better? – Zara Dec 02 '18 at 15:39
  • Well, if this is the case, yes, the first output will work better. – Vasilis G. Dec 02 '18 at 15:48
  • Perfect - thank you v much :) – Zara Dec 02 '18 at 15:50