Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
here is some code for it generating a list of words but i did not know how this code will work. can someone explain this code splist

Python
splits     = [(word[:i], word[i:]) for i in range(len(word) + 1)]
  deletes    = [a + b[1:] for a, b in splits if b]
Posted

1 solution

As it stands it will do nothing unless word is already a declared list. Try:
Python
# Create a simple list of words
#
word = [ "one","two","three"]

# Create a new list of pairs of elements of word.
# Each pair will be the first i entries and the remaining entries, as i
# goes from 0 to the number of words
#
splits     = [(word[:i], word[i:]) for i in range(len(word) + 1)]
splits

[([], ['one', 'two', 'three']), (['one'], ['two', 'three']), (['one', 'two'], ['three']), (['one', 'two', 'three'], [])]

# Create a list from each entry combining the first item
# with the last 1 to n of the second item, in each pair,
# ignoring any where the second item is null.
#
deletes    = [a + b[1:] for a, b in splits if b]
deletes

[['two', 'three'], ['one', 'three'], ['one', 'two']]


Take a look at https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions[^] for more information on list comprehensions.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900