>>> ['a', 'b'].index('b')
1
If the list is already sorted, you can of course do better than linear search.
Answer from AndiDog on Stack Overflow>>> ['a', 'b'].index('b')
1
If the list is already sorted, you can of course do better than linear search.
Probably the index method?
a = ["a", "b", "c", "d", "e"]
print a.index("c")
As others suggested, don't use list as a variable name. It is a type.
lists = ["22 + 13", "4500 - 2"]
for string in lists:
signPos = None
if "+" in string:
signPos = string.find("+")
elif "-" in string:
signPos = string.find("-")
else:
print('Error')
print(signPos)
# Output
# 3
# 5
signpos = list.find("+") or list.find("-")
If the string does not have a plus sign, the first find() call will return -1 which is a non-false value, so the second find() will not be executed, and signpos will be assigned -1.
This probably isn't what you wanted.
python - Finding specific characters within a list - Stack Overflow
Finding characters in a list python - Stack Overflow
python - Search for a char in list of lists - Stack Overflow
python - Searching for a character or string of characters in a list (like the find function on websites) - Stack Overflow
I'm really new to python and i'm having some trouble figuring out how to check if a list contains a certain character.
For example:
list = ['a1', 'a2', 'b1', 'b2', 'a3', 'a5', 'c3']
how would I check to see what elements contain the string 'a'? sorry if i didn't word my question properly i'm still very new to coding, but any help would be appreciated.
Maybe this could be an opportunity to introduce you to some python features:
from typing import List
def rare_char(sentence: str, rare_chars: List[str]=["j", "x", "q", "z"]) -> List[str]:
return [word for word in sentence.split() if
any(char in word for char in rare_chars)]
def cool_para(sentence: str) -> str:
return f"{len(rare_char(sentence))} word(s) with rare characters"
This answer uses:
- typing, which can be used by third party tools such as type checkers, IDEs, linters, but more importantly to make your intentions clear to other humans who might be reading your code.
- default arguments, instead of hardcoding them inside the function. It's very important to document your functions, so that an user would not be surprised by the result (see Principle of Least Astonishment). There are of course other ways of documenting your code (see docstrings) and other ways of designing that interface (could be a class for example), but this is just to demonstrate the point.
- List comprehensions, which can make your code more readable by making it more declarative instead of imperative. It can be hard to determine the intention behind imperative algorithms.
- string interpolation, which in my experience is less error prone than concatenating.
- I used the pep8 style guide to name the functions, which is the most common convention in the python world.
- Finally, instead of printing I returned a
strin thecool_parafunction because the code below the# DO NOT CHANGE CODE BELOWcomment is printing the result of the function call.
Ideally you want to use list comprehension.
def CoolPara(letters):
new = [i for i in text.split()]
found = [i for i in new if letters in i]
print(new) # Optional
print('Word Count: ', len(new), '\nSpecial letter words: ', found, '\nOccurences: ', len(found))
CoolPara('f') # Pass your special characters through here
This gives you:
['In', 'a', 'hole', 'in', 'the', 'ground', 'there', 'lived', 'a', 'hobbit.', 'Not',
'a', 'nasty,', 'dirty,', 'wet', 'hole,', 'filled', 'with', 'the', 'ends', 'of',
'worms', 'and', 'an', 'oozy', 'smell,', 'no', 'yet', 'a', 'dry,', 'bare,', 'sandy',
'hole', 'with', 'nothing', 'in', 'it', 'to', 'sit', 'down', 'on', 'or', 'to', 'eat;',
'it', 'was', 'a', 'hobbit-hole,', 'and', 'that', 'means', 'comfort']
Word Count: 52
Special letter words: ['filled', 'of', 'comfort']
Occurences: 3
Try this:-
lst = [['a', 'e'], ['g', 'j'], ['m', 'n', 'w'], ['z']]
def search(search_char):
result = [x for x in lst if search_char in x]
return result
print(search('g'))
For a start there is a keyword error in your variable - list is a keyword, try my_list.
This works for returning the list you want:
#Try this
my_list = [['a', 'e'], ['g', 'j'], ['m', 'n', 'w'], ['z']]
def check_for_letter(a_list,search):
for i in a_list[:]:
if search in a_list[0]:
return a_list[0]
else:
a_list[0] = a_list[1]
Session below:
>>> check_for_letter(my_list,"j")
['g', 'j']
>>>
This gives a list of indices:
[i for i, x in enumerate(vec) if "you" in x]
This is called a list comprehension, and it uses the enumerate function to keep track of the indices. If you aren't familiar with these, I recommend the official python tutorial here
I've got a lead!
Next, I added:::
for p in vec:
if 'yo' in p:
print p
print list1.index(p)
Sorry Patrick, this is more along the lines of what I wanted to do. Thanks anyways! -although I don't quite get what you were getting at. I'd like to know, though.
Here is completed program, don't know how I got here:::
import os
list1 = []
x = "/Users/User/temp"
vec = os.listdir(x)
for p in vec:
list1.append(p)
for line in list1:
print line
b = raw_input('search for item in list/path>>> ')
for p in vec:
if str(b) in p:
print p
print list1.index(p)
Woo Hoo -peer
find() returns -1 if the character is not found in the string. Anything that is not zero is equal to True. try if item.find("x") > -1.
You can use in again for strings:
num = ["one","two","threex"]
for item in num:
if "x" in item:
print("found")
Think in Strings as a list of chars like "ext" -> ['e', 'x', 't']
so "x" in "extreme" is True
Assume you have a list l = ['alpha', 'bravo', 'charlie.', 'delta', 'echo']
Then you can create a list with all words containing '.' in it by doing filter like below:
l = ['alpha', 'bravo', 'charlie.', 'delta', 'echo']
list_with_dot = [x for x in l if x.find('.') != -1]
If you want it without list comprehension:
sent = input('Enter sentence > ')
words = sent.split()
for word in words:
if "." in word:
print(word)
Also, you if you're in Python 2.7, use raw_input, input for Python 3.
"\"" in dfTrain['name'][22] is 'McGowan, Miss. Anna "Annie"' which contains "\"
while dfTrain['name'] is a list and you dont have a "\" as element in list
Similar example as yours:
>>> nested_list_example = ["abhishek","ralesh","wr'"]
>>> "wr'" in nested_list_example
True
>>> "'" in nested_list_example
False
>>> "'" in nested_list_example[2]
True
There can be several ways of doing this:
1) One of the things you can do is
"\"" in dfTrain['name'].to_string()
This returns True if any of the names in the df contain a ".
2) The other way could be not dfTrain[dfTrain['name'].str.contains('"')].empty
This is because, I am finding all columns that contain ".
If there are no columns that contain " it means the dataframe returned will be empty.
If the dataframe returned is empty(True) then none of the columns contain a " for which you want the output 'False' (hence the 'not' statement')
Check this.
Dictionary = ["Hello", "Hi"]
Character = ['e']
def findwords(dictionary,character):
tmp = ""
for i in dictionary:
#convert string to char list
str_arr = list(i)
for j in character:
#if char is in char list then save it in tmp variable
#if you want multiple values then use array instead of tmp
if j in str_arr:
tmp = i
return tmp
k = findwords(Dictionary,Character)
print(k)
This might clean up your code a bit, I think it is what you are going for...
Dictionary = ["Hello", "Hi"]
Character = ["e"]
def findwords(dictionary, character):
for i in dictionary:
if any(j in i for j in character):
return i
return ""
For all matches:
def findwords(dictionary, character):
matches = []
for i in dictionary:
if any(j in i for j in character):
matches.append(i)
if matches:
return ",".join(matches)
else:
return ""
It will see if anything in the substring matches your word. If it does, return the word, else ""
findwords(["Hello", "Hi"],["e"])
'Hello'
findwords(["Hello", "Hi"],["k"])
''
For your issue:
TypeError: list indices must be integers or slices, not list
for i in dictionary,character: <-- I will be list ['Hello', 'Hi']
for j in dictionary:
if character[i] == dictionary[i][j]: <---- you can't do character[i] where i is ['Hello', 'Hi']