Splitting a single index list into multiple list indexes? - python

I have a list:
lst = ['words in a list']
and I was hoping to split each one of these words in the string into their own separate indexes. So for example, it would look something like this:
lst = ['words','in','a','list']
I'm wondering if this is possible? I thought initially this would be just a simple lst.split() with a loop, but it seems like this is will throw an error.
Thanks for the help!

Use this:
print(lst[0].split())
If the list has more elements:
print([x for i in lst for x in i.split()])

Split only works for a string type. So you need to index the list item first and then split.
lst = lst[0].split()

Use this when you have a list of string or single string inside a list
lst = ['this is string1', 'this is string2', 'this is string3']
result =' '.join(lst).split()
print(result)
# output : ['this', 'is', 'string1', 'this', 'is', 'string2', 'this', 'is', 'string3']

Related

list in list, search in an another list [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
I have a first list, containing string lists and a second list containing strings. I want that when a string from the first list is found in the second, the string from the second is returned and the search resumes at the next string from the first list.
list1 = [
['test', 'string'],
['hello', 'world']
['good', 'morning','everyone']]
list2 = [
['test is here'],
['hi everyone'],
['world of code']]
If list1[0][0] is in list2[0], then return list2[0] and go to list1[1] (don't want to test list1[0][1]).
I've tried nesting for loops inside other for loops with break and if conditions but can't get the solution.
If the length of lists is the same, the code should be something like this:
list1 = [
['test', 'string'],
['hello', 'world'],
['good', 'morning', 'everyone']]
list2 = [
['test is here'],
['hi everyone'],
['world of code']]
answer = []
for l1 in range(len(list1)):
for item in list1[l1]:
if item in str(list2[l1]):
answer.append(item)
break
print(*answer)
and output will be
test
Hope this helped! :D
First, here are some tips for solving problems like this in the future:
First, the format of your input data is pretty strange (in my opinion), so I'd really recommend trying to flatten everything out -- this may or may not be possible depending on the larger structure of your program, so if you can't actually do that, then no big deal. Something like:
list1 = [ ['test', 'string'], ['hello', 'world'], ['good', 'morning', 'everyone'] ]
list2 = ['test is here', 'hi everyone', 'world of code']
is already easier to work with from a data processing standpoint, and that's just from flattening list2.
Second, conceptually, you have to have two loops going on here -- the first is to iterate through list1 (so if you find a match in list2, you can return the match and move onto the next member of list1), and another to go through the individual elements of list1, since a string in list2 could match on any one of the strings from the inner lists in list1 (i.e. a string in list2 could be matched either by 'test' or 'string').
With that said, here's a (pretty inefficient) solution to your problem:
def check_long_str(long_strings, check_list):
for check in check_list: #iterate over individual strings in each inner list of list1
for long_string_item in long_strings: #look for a match in list2
long_string = long_string_item[0] #weird format
if check in long_string:
print('"{}" found "{}"'.format(check, long_string))
return long_string
return None
def check_for_strings(search_strings, long_strings):
toReturn = set()
for search_list in search_strings: #iterate over inner lists of list1
found_str = check_long_str(long_strings, search_list)
if found_str is not None:
toReturn.add(found_str)
return toReturn
print(check_for_strings(list1, list2))
Output:
"test" found "test is here"
"world" found "world of code"
"everyone" found "hi everyone"
set(['test is here', 'hi everyone', 'world of code'])
So there was an error in the code you gave. I found an issue in the code you gave. There is a typo which is a missing "," after one of the lists. This is right after the:
['hello', 'world']
list in list1.
Although there may be better ways to loop through a nested list, this is how I would do it.
list1 = [
['test', 'string'],
['hello', 'world'],
['good', 'morning', 'everyone']]
list2 = [
['test is here'],
['hi everyone'],
['world of code']]
found_words = []
for i in range(len(list1)):
for x in range(len(list1[i])):
for z in list2:
for y in z:
teststring = y.split()
for j in teststring:
if j in list1[i][x]:
found_words.append(j)
break
print(found_words)
Output:
['test', 'world', 'everyone']
Hopefully this helps!

Split The Second String of Every Element in a List into Multiple Strings

I am very very new to python so I'm still figuring out the basics.
I have a nested list with each element containing two strings like so:
mylist = [['Wowza', 'Here is a string'],['omg', 'yet another string']]
I would like to iterate through each element in mylist, and split the second string into multiple strings so it looks like:
mylist = [['wowza', 'Here', 'is', 'a', 'string'],['omg', 'yet', 'another', 'string']]
I have tried so many things, such as unzipping and
for elem in mylist:
mylist.append(elem)
NewList = [item[1].split(' ') for item in mylist]
print(NewList)
and even
for elem in mylist:
NewList = ' '.join(elem)
def Convert(string):
li = list(string.split(' '))
return li
print(Convert(NewList))
Which just gives me a variable that contains a bunch of lists
I know I'm way over complicating this, so any advice would be greatly appreciated
You can use list comprehension
mylist = [['Wowza', 'Here is a string'],['omg', 'yet another string']]
req_list = [[i[0]]+ i[1].split() for i in mylist]
# [['Wowza', 'Here', 'is', 'a', 'string'], ['omg', 'yet', 'another', 'string']]
I agree with #DeepakTripathi's list comprehension suggestion (+1) but I would structure it more descriptively:
>>> mylist = [['Wowza', 'Here is a string'], ['omg', 'yet another string']]
>>> newList = [[tag, *words.split()] for (tag, words) in mylist]
>>> print(newList)
[['Wowza', 'Here', 'is', 'a', 'string'], ['omg', 'yet', 'another', 'string']]
>>>
You can use the + operator on lists to combine them:
a = ['hi', 'multiple words here']
b = []
for i in a:
b += i.split()

Merge the matches from regular expressions into a single list

I am trying to separate a string in CamelCase into a single list
I managed to separate the words with regular expressions
But I am clueless on how create a single list of all the matches
I tried to concatenate the lists, append something like that but I don't think it would work in my case
n="SafaNeelHelloAByeSafaJasleen"
patt=re.compile(r'([A-Z][a-z]*|[a-z$])')
matches=patt.finditer(n)
for match in matches:
a=match.group()
list=a.split()
print(list)
output:
['Safa']
['Neel']
['Hello']
['A']
['Bye']
['Safa']
['Jasleen']
Desired output:
['Safa','Neel','Hello','A','Bye','Safa','Jasleen']
You're looking for re.findall(), not re.finditer():
>>> string = "SafaNeelHelloAByeSafaJasleen"
>>> pattern = re.compile(r"([A-Z][a-z]*|[a-z$])")
>>> pattern.findall(string)
['Safa', 'Neel', 'Hello', 'A', 'Bye', 'Safa', 'Jasleen']
You can append the matches to new list:
new_list=[]
for match in matches:
a=match.group()
new_list.append(a)
Output of new_list:
['Safa', 'Neel', 'Hello', 'A', 'Bye', 'Safa', 'Jasleen']

Python range of a list?

I'd like to be able to get a range fields of a list.
Consider this:
list = ['this', 'that', 'more']
print(list[0-1])
where the [0-1] should return the first and second fields.
You will want to use Python's slice notation for this:
>>> lst = ['this', 'that', 'more']
>>> print(lst[:2])
['this', 'that']
>>>
The format for slice notation is [start:stop:step].
Also, I changed the name of the list to lst. It is considered a bad practice to name a variable list since doing so overshadows the built-in.
use:
list = ['this', 'that', 'more']
print(list[0:2])

Remove trailing newline from the elements of a string list

I have to take a large list of words in the form:
['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
and then using the strip function, turn it into:
['this', 'is', 'a', 'list', 'of', 'words']
I thought that what I had written would work, but I keep getting an error saying:
"'list' object has no attribute 'strip'"
Here is the code that I tried:
strip_list = []
for lengths in range(1,20):
strip_list.append(0) #longest word in the text file is 20 characters long
for a in lines:
strip_list.append(lines[a].strip())
You can either use a list comprehension
my_list = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
stripped = [s.strip() for s in my_list]
or alternatively use map():
stripped = list(map(str.strip, my_list))
In Python 2, map() directly returned a list, so you didn't need the call to list. In Python 3, the list comprehension is more concise and generally considered more idiomatic.
list comprehension?
[x.strip() for x in lst]
You can use lists comprehensions:
strip_list = [item.strip() for item in lines]
Or the map function:
# with a lambda
strip_list = map(lambda it: it.strip(), lines)
# without a lambda
strip_list = map(str.strip, lines)
This can be done using list comprehensions as defined in PEP 202
[w.strip() for w in ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']]
All other answers, and mainly about list comprehension, are great. But just to explain your error:
strip_list = []
for lengths in range(1,20):
strip_list.append(0) #longest word in the text file is 20 characters long
for a in lines:
strip_list.append(lines[a].strip())
a is a member of your list, not an index. What you could write is this:
[...]
for a in lines:
strip_list.append(a.strip())
Another important comment: you can create an empty list this way:
strip_list = [0] * 20
But this is not so useful, as .append appends stuff to your list. In your case, it's not useful to create a list with defaut values, as you'll build it item per item when appending stripped strings.
So your code should be like:
strip_list = []
for a in lines:
strip_list.append(a.strip())
But, for sure, the best one is this one, as this is exactly the same thing:
stripped = [line.strip() for line in lines]
In case you have something more complicated than just a .strip, put this in a function, and do the same. That's the most readable way to work with lists.
If you need to remove just trailing whitespace, you could use str.rstrip(), which should be slightly more efficient than str.strip():
>>> lst = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
>>> [x.rstrip() for x in lst]
['this', 'is', 'a', 'list', 'of', 'words']
>>> list(map(str.rstrip, lst))
['this', 'is', 'a', 'list', 'of', 'words']
my_list = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
print([l.strip() for l in my_list])
Output:
['this', 'is', 'a', 'list', 'of', 'words']

Categories