Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a list
dl[vr]
where vr is an arbitrary name extracted from a file.
what I want is to create an array with the same name as vr,
so I wonder besides
ar = np.array(dl[vr])
what should I do to name the array the same as the variable vr?
thanks
I am not entirely sure what you're asking for, but it sounds like you want an arbitrary string from a file used to identify an array (presumably filled with data from that same file).
Rather than trying to give the variable itself that arbitrary name, I think you would be better off storing the array in a dictionary and using the arbitrary name as the key:
arrayDict = {}
name = readStringFromFile()
data = readArrayFromFile()
arrayDict[name] = data
Obviously, you should choose more appropriate names for these variables if you can :)
You could create a new variable with an unknown name, but then you would have to access it indirectly as well. You might as well make this more obvious with your own dictionary.
I think you are totally confused with basics.
listA = ['A','C','1']
here listA is a list
dictA = {}
dictA["name"] = "xxxxxxx"
here dictA is a dict
Following links will help you to understand what is list(array)/dict :
https://docs.python.org/2/library/stdtypes.html#mapping-types-dict
https://docs.python.org/2/tutorial/datastructures.html
You can use globals() or locals()
globals()['aaa'] = 'hello world'
print aaa
'hello world'
But in my opinion better use dictionary.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to add an element to a list, but the list might not exist yet. In which case, I'd create a list of that single element. It might be an entry in a dictionary. It's my responsibility to add to a particular field - hence the append. But, if it's the first time I'm doing it, the key doesn't even exist in the dictionary yet. Hence the set to a list of a single element.
So in a nutshell, the following
if 'dependencies' in userdata:
userdata['dependencies'].append('foo')
else:
userdata['dependencies'] = ['foo']
This feels very unpythonic and ugly. What are some better options?
use try...except like below:
try:
X.append('foo')
except NameError:
print("you need create list first. I create list for you. then append.")
X = ['foo']
EDIT : base on your editing question:
from collections import defaultdict
userdata = defaultdict(list)
userdata['dependencies'].append('foo')
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have the below JSON response, I want to write a function that:
runs through the response looking for a match of 'risk-level' = [medium OR high]
if match found returns the corresponding alert-id in a list / array format (I think we should use .append here)
if no match is found, exit the program (I'm pretty sure it would "exit()" here)
I have managed to get it to match / find one input and bring back that response, I'm just struggling with feeding it a list with an "OR" logic to bring back an independent result.
[
{'event-num': 5520, 'alert-id': '6e310403-ca53-32ut-aec6-16ffc648f7b7', 'risk-level': 'very-low'},
{'event-num': 5521, 'alert-id': '0a6b15b7-3db3-2x7t-b4ab-b023cfb85eaf', 'risk-level': 'low'},
{'event-num': 5523, 'alert-id': '6e310403-3db3-4b5f-cehd-16ffc648f7b7', 'risk-level': 'medium'},
{'event-num': 5523, 'alert-id': '0a6b15b7-6ty5-4b5f-cehd-b023cfb85eaf', 'risk-level': 'high'}
]
You could use .append() as you mentioned, or, you could do this in a quick list comprehension.
Let's say your list is called events.
risky_events = [event['alert-id']
for event in events
if event['risk-level'] in {'medium','high'}]
The above code simply creates a list of matching risk levels. How would you use the snippet above to implement your exit() requirement? You would need to check if the list created above was empty. Give it a try.
What went wrong in the approach you took? Did you try using .append() yourself? Look up the Python docs section on lists to understand how append works, and give that approach a try.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
So in my niche use case I want to create a hash map in python to store a large list dataset. This list has a key value as a tuple (i.e (1,2)) and my goal is to search the list and see if the tuple exists.
I know this is achievable with a regular list but I wanted the time complexity of O(1) with the hash map functionality. But when adding elements to the dictionary, I am doing this:
dictionary[(1,2)] = None
Because I couldn't care less about the value associated with the key.
Is this good coding practice or is there something else I should use?
If you don't give a toss about the value, you can use a set. From the python source code (line 4 of Objects/setobject.c):
Derived from Lib/sets.py and Objects/dictobject.c.
If you need to iterate over a set, you should use a list or do the conversion as needed.
I would suggest using defaultdict. By default, any values not in the dictionary would be False.
from collections import defaultdict
lookup = defaultdict(bool)
lookup[(1,2)] = True
Examples:
l = [(1,2), (3,4), (5,6)]
for e in l:
lookup[e] = True
print(lookup[(3,4)])
# True
print(lookup[(8, 9)])
# False
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a file from which I have to do some training from data.
This file contains some words.
I'd like to create a list which contains another list. The second list, is made of a key-value pair.
For example:
The word Will can be either a name or a modal.
My list should be something like that:
Will --> 1.[Key]Noun : [Value] some-number --> 2. [Key]Modal: [Value] some-other-number
How can I implement this in Python?
I believe that in Java this could be implemented using an Hashmap which contains another hashmap if i'm not mistaken.
I think you are thinking of dictionaries, not lists. Lists in python are akin to arrays, Dictionaries are as you guess similar to hashmaps, and can only have unique keys, but can hold other dictionaries. You can also have a list of dictionaries, or a dictionary of lists.
For your project I'm just guessing you want something like.
words={"Will":{"Noun":1,"Modal":2}}
which you would then access by doing
>>> print(words)
{'Will': {'Noun': 1, 'Modal': 2}}
>>> print(words["Will"])
{'Noun': 1, 'Modal': 2}
>>> print(words["Will"]["Noun"])
1
>>> print(words["Will"]["Modal"])
2
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
At every step shall I be introducing a new variable name or I can continue to use the same name. Kindly advise what's the best practice and why?
df1 = df.withColumn('last_insert_timestamp', lit(datetime.now())
df2 = df1.withColumn('process_date', lit(rundate)
Versus
df = df.withColumn('last_insert_timestamp', lit(datetime.now())
df = df.withColumn('process_date', lit(rundate)
There is no best practice for that. It depends on what you want to do.
In Python, variables are just labels assigned to an object. So if you need your original DF object to be modified through your code then change the assignment to the newly generated DF.
Now, if you need to keep the first DF for other processing later in the code, then you may assign a new variable name.
You might find more explanations here: Reassigning Variables in Python
You can use like this
df = df.withColumn('last_insert_timestamp', lit(datetime.now()) \
.withColumn('process_date', lit(rundate)