I have a problem with lists because I want to get value from the list named test_table with value from A_table as an argument. Is there any way to get the proper result? Of course the lists aren't empty and when I run it I get Process finished with exit code -1073740791 (0xC0000409)
for x in range(len(A_table)):
print(test_table[A_table[x]])
Edit:
List_A is generated like this: (i think that the problem is type-string not integer, but with int type my function doesn't work):
A_letter = [find_all(sentence, 'A')]
A_string = ' '.join(map(str, A_letter[0]))
data = A_string.split() # split string into a list
for temp in data:
A_table.append(temp)
Is this what you are trying to do?
This code looks into test_list and if the value is found, prints it by calling the list.index() function.
list_a =[1,2,3,4]
test_list = [3,5,8,9]
for i in range(len(list_a)):
if list_a[i] in test_list:
print(test_list[test_list.index(list_a[i])])
//output = 3
To start, I don't know where that find_all function is defined, but if it behaves like re.findall (which you should probably use), then it returns a list already, so by defining A_letter = [find_all(sentence, 'A')], you have a list of list of matches.
Consider this example:
>>> import re
>>> sentence = 'A wonderful sample of A test string'
>>> re.findall('A', sentence)
['A', 'A']
Moving on, your A_table has a list of str. So there is no direct way to index into another list using the values inside of A_table. For example, even if test_table has the values ['A', 'B', 'C'], the valid index values are still "0", "1", and "2", i.e. I cannot get test_table['A'], because lists may only be indexed by int.
If you want to get the index of a certain value (e.g. "A") in a list, you can use the index function of list, which returns the first index of the provided value, or raises a ValueError if the value is not found.
For example:
>>> import re
>>>
>>> test_table=['Q','F','R','A','B','X']
>>>
>>> sentence = 'A wonderful sample of A test string'
>>> A_table = re.findall('A', sentence)
>>>
>>> for match in A_table:
... # first check to ensure the match is in the test_table
... if match in test_table:
... # ok, I know it is here, so get the index
... i = test_table.index(match)
... v = test_table[i]
... print(f'index [{i}] has value [{v}]')
...
index [3] has value [A]
index [3] has value [A]
Edit:
Here is some more info on the .index function, and here is another link to a question that indicates your present error is related to memory corruption.
Related
I'm trying to create a new column that compares two lists and returns the matching string.
I keep getting the error "'list' object has no attribute 'find'".
I'm still a novice at this so any help would be really appreciated!
I'm trying to use python and pandas for this
What I have so far is
raw = pd.read_csv(r"")
brandnames = ['Amana','Maytag']
raw['Brands'] = [k for k in raw['Description'] if brandnames.find(k)]
raw.head()
I want the end result to have a new column named Brands that say 'Amana' when the Description column contains the words 'Amana'
Thank you so much!
I'm confused as to why you are confused. The find documentation clearly states that it's a string method, not list. Also, it returns an index. You've invented a find method that returns a Boolean and is a new element of class list.
I think what you want is
[k for k in raw['Description'] if k in brandnames]
More directly, you could do this with set intersection. Turn both name lists into sets, take the intersection, and convert to a list.
list(set(raw['Description']) * set(brandnames))
There is no "find" method or property in the list type (brandnames), so Python is throwing an error. For a quick check of the available properties and methods in a type, you can use dir(), e.g.:
>>> x = ['abc', 'def']
>>> dir(x)
['__add__', '__class__', '__contains__', '__delattr__', ...
What you probably wanted was the in operator like in Prune's answer. One thing worth considering is that in will only return True if an exact match is found:
>>> brandnames = ['Amana', 'Maytag']
>>> 'Amana' in brandnames
True
>>> 'Amana ' in brandnames
False
>>> 'amana' in brandnames
False
>>> 'Amanaa' in brandnames
False
Another thing to consider is you may need to do make additional changes to result returned from pd.read_csv before you can use the in operator on it.
>>> some_data = "foo bar baz Maytag"
>>> [i for i in some_data.split(' ') if i in brandnames]
['Maytag']
Calling type() on raw in your program might work, but if not, I would suggest having a look at the Pandas documentation.
Given the data for the row index to be found as max_sw and list is sw_col.
I tried this and some other variation, but nothing worked.
print(i for i in range(len(sw_col)) if sw_col[i]== max_sw)
The line you have is almost there. If you put the generator into a list and use only index position zero, this will give you the correct answer:
sw_col = ['a','b','c']
max_sw = 'c'
print([i for i in range(len(sw_col)) if sw_col[i]== max_sw][0]) # prints 2
A more concise solution would be to look up the item directly in the list, like so:
sw_col = ['a','b','c']
max_sw = 'c'
print(sw_col.index(max_sw)) # prints 2
This is my list:
l = ['today','is','a','holiday','but','nothing','to','do']
I wish to put the items after 'but' into another list such as:
another_list = ['nothing','to','do']
I tried the following way:
l = ['today','is','a','holiday','but','nothing','to','do']
for element in l:
parts = element.split('but')
But it does not provide the output I expected.
You are splitting on an array element not a string.. so in this case you a split isn't going to work. There is nothing to split. Instead find the index and continue from there. Checkout https://www.tutorialspoint.com/python/python_lists.htm to learn more about python list
l = ['today','is','a','holiday','but','nothing','to','do']
# get the index of but
i = l.index("but") # "This method returns index of the found object otherwise raise an exception indicating that value does not find."
# print everything after "but" using slice logic.
print l[i+1:]
You can use index:
l[l.index('but')+1:]
>>> ['nothing', 'to', 'do']
Join the list, partition it, and then re-split it.
' '.join(l).partition('but')[-1].split() # ['nothing', 'to', 'do']
I am trying to solve this problem: I have some symbols:
list =["RBS-UK", "GOOG-US"]
Now I have to transform all the region occurrences of "UK" to "GB". I could have done this easily:
new_list =[]
for symbol in list :
temp_list=symbol.split("-")
if temp_list[1]=="UK":
temp_list[1]="GB"
new_list.append("-".join(temp_list))
But can I do this without the equality comparision?
I am looking for something along the lines of:
some_dict={}
new_list =[]
for symbol in list :
temp_list=symbol.split("-")
temp_list[1]=some_dict(temp_list[1]) # So this dict returns GB if its UK else returns same value as it is
new_list.append("-".join(temp_list))
Is it possible to do this, or are there any other solutions?
Yeah! sure
ls =['RBS-UK','GOOG-US']
map(lambda x: x.replace('-UK', '-GB'), ls)
You are looking for a lookup, for which a dictionary will work:
translations = {'UK':'GB'} # and so on
for symbol in lst:
country_code = symbol.split('-')[1]
translated = translations.get(country_code,country_code)
new_list.append('{}-{}'.format(symbol.split('-')[0],translated))
The key line is:
translated = translations.get(country_code,country_code)
Dictionary have a method get() which will return None if the key is not found. We use this to avoid raising KeyError. get() takes an optional second parameter for a value to return other than None if the key is not found.
In the snippet above, we pass the country code to get(), and ask it to return the same country code if there isn't a translation available, otherwise return the translation.
The second line uses string formatting to reconstruct the original symbol with the translated code and appends it to your list.
You don't actually have to redefine the offset. You can simply replace the string:
for symbol in list:
symbol = symbol.replace('-UK','-GB')
If the string is encountered it will be replaced, otherwise it is left alone entirely.
If you really want to use a dict, you could use the dict.get method, which accepts a default argument used when the key isn't found, and so some_dict.get(x,x) means "return the value associated with x if it exists, otherwise return x":
>>> some_dict = {"UK": "GB"}
>>> country = "UK"
>>> some_dict.get(country, country)
'GB'
>>> country = "CA"
>>> some_dict.get(country, country)
'CA'
You can use the sub function from the re module useful for regular expression operations.
Here is a one-liner which produces the list you want:
import re
newlist = [re.sub('UK','GB', symbol) for symbol in list]
I'd like to:
Check a key / value at position i
Check to see if key / value contains a string
delete / store in another variable either the key / value
The equivelant of this Java code:
//Some list...
ArrayList<String> example;
...
//Index into data structure
example.get(i);
//Check for some string...
if (example.get(i).contains("someText")){
somestuff;
}
//Store in some other variable
exam = example.get(i)
That's what I'm effectively trying to in Java, however I'd like to be able to do that with Python dictionarties however I'm not sure if this is possible, as I find the Python documentation rather hard to read.
Python dictionaries are implemented as hash tables, so there is no intrinsic ordering; therefore, "position i" is a totally nonsensical concept for a dict -- it's like asking for the dict entry that's most yellow, or that least resembles a llama... those concepts just don't apply to dict entries, and "position i" is just as totally inapplicable.
Where does that i come from, i.e., what's the real issue you're trying to solve? If your requirement is to iterate over the dictionary, you do that directly, without the crutch of a "numeric index". Or, if you do need to keep some specific order or other, then you don't use a dict, but rather some different data structure. If you explain exactly the purpose you're trying to address, I'm sure we can help you.
Direct translation (for an ArrayList<String>, you do not want a dictionary, you want a list):
example = ["foo", "bar", "baz"]
str = example[i]
if "someText" in str:
somestuff()
Get used to the for keyword, though, it's awesome in Python:
for str in example:
if "someText" in str:
someStuff()
Here's an example using dictionaries:
fruits = {
"apple": "red",
"orange": "orange",
"banana": "yellow",
"pear": "green"
}
for key in fruits:
if fruits[key] == "apple":
print "An apple is my favorite fruit, and it is", fruits[key]
else:
print "A", key, "is not my favorite fruit, and it is", fruits[key]
Iteration using for on a dictionary results in the keys, it's still up to you to index the item itself. As Alex pointed out, we're really off-base answering you with so little information, and it sounds like you're not well-rooted in data structures (dictionaries will probably yield a different order every time you iterate it).
Yo can do that to reproduce the same behavior that your example in Java.
# Some list
example = {} # or example = dict()
...
# Index into data estructure.
example[example.keys(i)]
# Check for some string...
if example[example.keys(i)] == 'someText' :
pass
# Store in some other variable...
exam = example[example.keys(i)]
del example[example.keys(i)]
# ...or
exam = example.pop(example.keys(i))
What's nice about Python is that you can try code interactively.
So we create a list which is like a Java List:
>>> mylist = ["python","java","ruby"]
>>> mylist
['python', 'java', 'ruby']
We can get an entry in the list via its index:
>>> mylist[0]
'python'
And use the find function to search for substrings:
>>> mylist[1].find("av")
1
>>> mylist[1].find("ub")
-1
It returns -1 if the string isn't found.
Copying an entry to a new variable is done just how you'd expect:
>>> newvalue = mylist[2]
>>> newvalue
'ruby'
Or we can create a dict which is like a Java Map, storing by key rather than index, but these work very similarly to lists in Python:
>>> mydict = { 'python':'Guido', 'java':'James', 'ruby':'Yukihiro' }
>>> mydict['java']
'James'
>>> othervalue = mydict['ruby']
>>> othervalue
'Yukihiro'
>>> mydict['python'].find('uid')
1
>>> mydict['python'].find('hiro')
-1
>>> mydict['ruby'].find('hiro')
4