This question already has answers here:
Python copy a list of lists [duplicate]
(3 answers)
Closed 1 year ago.
segp2=[['13s'],['3c','6h','8h','9h','10c','11h'],['4c','4h','5c','5h','7c','7s'],[],[],[],['4h','5h','6h','8h','9h','11h'],[],[]]
copyseg=list(segp2)
copy=list(copyseg[6]);x=0;y=0
for i in copyseg[1]:
if i in copyseg[6]:copyseg[1].remove(i);copy.remove(i);x+=1
if x==5:break
for i in copyseg[2]:
if i in copyseg[6]:copyseg[2].remove(i);copy.remove(i);x+=1
if x==5:break
for i in copyseg[3]:
if i in copyseg[6]:copyseg[3].remove(i);copy.remove(i);x+=1
if x==5:break
print(segp2)
print(copyseg)
These 2 are somehow coming out the same, even though segp2 is literally untouched. Using 'copyseg=list(segp2)' in my experience makes a copy of the list that is unaffected by new code. Yet somehow, everything I do on the 'copyseg' list is copied onto the 'segp2' list. I've tried everything I can think of and can't figure out why it's doing this.
You should do a deep copy of the seg2 list:
import copy
copyseg = copy.deepcopy(segp2)
or, if your list is only one-level deep,
copyseg = [list(lst) for lst in segp2]
Related
This question already has answers here:
What do ellipsis [...] mean in a list?
(5 answers)
Closed 2 years ago.
I've run into this unseen list object, when I tried to play with list append, and I've searched hard but unable to find much information. So this is what's happening:
L = ['dinosaur']
L.append(('theropoda', L))
print(L)
# ['dinosaur', ('theropoda', [...])]
Questions - what's the [...] means here? Thanks.
As mentioned in the comments, Python will not attempt to include a circular/recursive reference in the representation of a list.
It would appear that the __repr__ function (also used by lists to create the string for printing) is implemented via reprlib with recursive support. Without it, you would end up with a RecursionError as to output the list, Python must include the nested version of the list, which also needs the nested version, and so on. Instead, it outputs the special value of ... which indicates to you that it is a recursive reference.
This question already has answers here:
What does "list comprehension" and similar mean? How does it work and how can I use it?
(5 answers)
Closed 3 years ago.
I have scoured the internet and I cannot find any reference to this type of for loop:
variable = [(item["attribute1"], item["attribute2]") for item in piece_of_json_data]
I am using this to update wtform's SelecField choices:
form.SelectField.choices = variable
but I can only get it to work if I replace one of the attributes in parenthesis with a static number:
variable = [(1, item["attribute2"]) for item in piece_of_json_data]
but that sets the value of the option field to "1", when I need the option values to be one of the attributes as a string.
Does this create a dict? a tuple? is there some kind of terminology for this that I can use to find documentation?
Thanks to the comments, I now understand that I am using list comprehension to create a tuple. The tuple works fine with both string and integer values. My issue has to do with .choices not accepting a string.
I found that my only problem is that I had coerce set to int on my selectfield, so naturally it wanted an integer.
This question already has answers here:
What is the purpose of the single underscore "_" variable in Python?
(5 answers)
Trying to understand Python loop using underscore and input
(4 answers)
Closed 4 years ago.
I was check a solution on hacker rank where i was solving a question asking to print the name of the person with the second highest score from an input which has to be converted to a nested list first .
I understood all the logic in the code and most part of the code but why the Underscore ( _ ) in the for loop .Please explain me the code if there is a different concept .
marksheet = []
for _ in range(0,int(input())):
marksheet.append([input(), float(input())])
second_highest = sorted(list(set([marks for name, marks in marksheet])))[1]
print('\n'.join([a for a,b in sorted(marksheet) if b == second_highest]))
It's a Pythonic convention to use underscore as a variable name when the returning value from a function, a generator or a tuple is meant to be discarded.
In your example, the code inside the for loop does not make any use of the values generated by range(0,int(input())), so using an underscore makes sense as it makes it obvious that the loop does not intend to make use of it.
This question already has answers here:
Why does [1].append(2) evaluate to None instead of [1,2]? [duplicate]
(2 answers)
Appending to list in Python dictionary [duplicate]
(3 answers)
Closed 5 years ago.
I have an empty dictionary. The value of each key is to be a list. As I process through my data, I'm trying to add a list entry to a dictionary key's value, including possibly creating the key entry, in one line, and I can't figure out why it's not working.
Single set of data just for the example.
This works. It adds a new key, and adds the first entry in the value list to that key.
dates = dict()
mmdd = '3/24'
year = 2018
# -----------------------
# these three lines look they should be able to be combined
tmp = dates.get(mmdd,[])
tmp.append(year)
dates[mmdd] = tmp
# -----------------------
print(dates) # {'3/24': [2018]}
This doesn't.
dates = dict()
mmdd = '3/24'
year = 2018
dates[mmdd] = dates.get(mmdd,[]).append(year)
print(dates) # {'3/24': None}
Why doesn't it work? It appears (to me) to be doing the same thing. Everything before the .append returns a list, either with data in it or empty, and the append should add an entry to the list. It works when done piecemeal, but not when done at one time. What is wrong and/or missing from the above one-liner?
(I understand that the None means that it's actually the first two lines that aren't working, i .e.
tmp = dates.get(mmdd,[]).append(year)
is returning None instead of [2018]. But that isn't helping me figure it out, either.)
(I've played with the one-liner in several ways just to see if I could get it work, e.g. I tried putting an extra set of parens around everything before the .append, same with brackets, etc. I've also searched around but haven't been able to find anything.)
I'm not looking for other ways to solve the problem (I can use defaultdict, etc.). I'm specifically looking for why the above one-liner doesn't work. There's a gap in my python understanding and I want to fill it. I have no doubt it's something immediately intuitive to the most casual observer. Nevertheless, I can't figure it out.
Thanks!
This question already has answers here:
Find file name from full file path
(4 answers)
Closed 9 years ago.
This should be dead simple, but I can't figure it out. I have a string that represents a path name to a file, ie
"C:/blah/this/whatever/filename"
And I need to extract the filename (programatically). I am trying to use strsplit (or str_split) and, it is easy enough to split the string by '/' but.. I cannot fathom how to actually extract one of the values in the returned vector, or determine how many elements are even in the vector (as that may very for my application). Using length (oddly enough, to my mind) does not help. Help?
Taken from: Find file name from full file path
basename("C:/some_dir/a")
> [1] "a"
dirname("C:/some_dir/a")
>[1] "C:/some_dir"
Although I think the above approach is much better, you can also use the str_split approach - which I really only mention to show how to select the last elements from a list using lapply.
example <- c("C:/some_dir/a","C:/some_dir/sdfs/a","C:/some_dir/asdf/asdf/a")
example.split <- strsplit(example,"/")
files <- unlist(lapply(example.split, tail , 1 ))
Don't need str_split:
sub( "^.+/(.+)$", "\\1", "C:/blah/this/whatever/filename" )