我有一个名为的父列表parent_list
,以及我要过滤的两个子集parent_list
.这些子集也是python列表,它们被称为filter1
和filter2
.
我可不可以做:
final_list = [object for object in parent_list if object.pk not in filter1 or filter2]
Run Code Online (Sandbox Code Playgroud)
或者我是否需要单独进行此过滤,如:
intermediate_list = [object for object in parent_list if object.pk not in filter1]
final_list = [object for object in intermediate_list if object.pk not in filter2]
Run Code Online (Sandbox Code Playgroud)
我无法从python列表推导的文档中明确找到答案.
所以我指的是另一个模型:
subscriptions = models.ManyToManyField(Season)
Run Code Online (Sandbox Code Playgroud)
所以我用:
@api_view(['POST'])
def buy_season(request):
_id = 1
season = Season.objects.get(id = _id)
a = ExtUser.subscriptions.add(season)
a.save()
return Response({'status': 'success'}, status=status.HTTP_200_OK)
Run Code Online (Sandbox Code Playgroud)
我得到一个错误对象'ManyToManyDescriptor',它不直接将“添加”属性设为多对多,而不是通过“抛出”,为什么会出现此错误?
我有一个简单的方法。条目是时间表应用程序中的条目,员工可在其中输入其工作时间。
class Entry(m.Model):
""" Represents an entry in a time_sheet. An entry is either for work, sick leave or holiday. """
# type choices
WORK = 'w'
SICK = 's'
VACATION = 'v'
type_choices = (
(WORK, 'work'),
(SICK, 'sick leave'),
(VACATION, 'vacation'),
)
# meta
cr_date = m.DateTimeField(auto_now_add=True, editable=False, verbose_name='Date of Creation') # date of creation
owner = m.ForeignKey(User, editable=False, on_delete=m.PROTECT)
# content
type = m.CharField(max_length=1, choices=type_choices, default='w')
day = m.DateField(default=now)
start = m.TimeField(blank=True) # starting time
end = …
Run Code Online (Sandbox Code Playgroud) 我正在从这样的泡菜文件加载数据集
""" Load the dictionary containing the dataset """
with open("final_project_dataset.pkl", "r") as data_file:
data_dict = pickle.load(data_file)
Run Code Online (Sandbox Code Playgroud)
它工作正常并正确加载数据。这是一行的示例:
'GLISAN JR BEN F': {'salary': 274975, 'to_messages': 873, 'deferral_payments': 'NaN', 'total_payments': 1272284, 'exercised_stock_options': 384728, 'bonus': 600000, 'restricted_stock': 393818, 'shared_receipt_with_poi': 874, 'restricted_stock_deferred': 'NaN', 'total_stock_value': 778546, 'expenses': 125978, 'loan_advances': 'NaN', 'from_messages': 16, 'other': 200308, 'from_this_person_to_poi': 6, 'poi': True, 'director_fees': 'NaN', 'deferred_income': 'NaN', 'long_term_incentive': 71023, 'email_address': 'ben.glisan@enron.com', 'from_poi_to_this_person': 52}
Run Code Online (Sandbox Code Playgroud)
现在,如何获得特征的数量?例如(salary, to_messages, .... , from_poi_to_this_person)
?
我通过打印整个数据集 ( print data_dict
)得到了这一行,这是结果之一。我想知道有多少特征是通用的,即在整个数据集中没有指定字典中的键。
谢谢
我不能使用Numpy或任何其他库函数,因为这是我必须要做的一个问题,我必须定义自己的方式.
我正在编写一个函数,它将两个列表(2维)作为参数.该函数应计算两个列表的元素乘积并将它们存储在第三个列表中,并从函数返回该结果列表.输入列表的示例是:
[[2,3,5,6,7],[5,2,9,3,7]]
Run Code Online (Sandbox Code Playgroud)
[[5,2,9,3,7],[1,3,5,2,2]]
Run Code Online (Sandbox Code Playgroud)
该函数打印以下列表:
[[10, 6, 45, 18, 49], [5, 6, 45, 6, 14]]
Run Code Online (Sandbox Code Playgroud)
也就是说2*5=10
,3*2=6
,5*9=45
...等等.
这是我下面的代码,但它仅适用于里面有2个列表(元素)的列表,就像上面的例子一样,并且完全可以正常工作,但我想要的是编辑我的代码,这样无论多少个列表(元素)存在于二维列表中,它应该在一个新的二维列表中打印出它的元素产品,例如它也应该适用于
[[5,2,9,3,7],[1,3,5,2,2],[1,3,5,2,2]]
Run Code Online (Sandbox Code Playgroud)
要么
[[5,2,9,3,7],[1,3,5,2,2],[1,3,5,2,2],[5,2,9,3,7]]
Run Code Online (Sandbox Code Playgroud)
或整个列表中的任意数量的列表.
def ElementwiseProduct(l,l2):
i=0
newlist=[] #create empty list to put prouct of elements in later
newlist2=[]
newlist3=[] #empty list to put both new lists which will have proudcts in them
while i==0:
a=0
while a<len(l[i]):
prod=l[i][a]*l2[i][a] #corresponding product of lists elements
newlist.append(prod) #adding the products to new list
a+=1
i+=1
while i==1: …
Run Code Online (Sandbox Code Playgroud) 假设我有一串小写字母,例如
'ablccmdnneofffpg'
Run Code Online (Sandbox Code Playgroud)
我的目标是找到这个字符串中连续数字的最长序列,在这种情况下是:
'abcdefg'
Run Code Online (Sandbox Code Playgroud)
直观的尝试是在每个字母周围找到循环并从该字母开始获得最长的序列.一种可能的解决方案是
longest_length = 0
start = None
current_start = 0
while current_start < len(word) - longest_length:
current_length = 1
last_in_sequence = ord(word[current_start])
for i in range(current_start + 1, len(word)):
if ord(word[i]) - last_in_sequence == 1:
current_length += 1
last_in_sequence = ord(word[i])
if current_length > longest_length:
longest_length = current_length
start = current_start
while (current_start < len(word) - 1 and
ord(word[current_start + 1]) - ord(word[current_start]) == 1):
current_start += 1
current_start += 1
Run Code Online (Sandbox Code Playgroud)
有没有其他方法可以用更少的线来解决问题,甚至使用一些pythonic方法?
需要在路径中的斜杠后获取最后一个文件夹或元素.换句话说,我有:
path = '/Users/ivanmac/Desktop/dogs_vs_cel/thumbnails_features_deduped_sample/'
Run Code Online (Sandbox Code Playgroud)
我需要得到:
'thumbnails_features_deduped_sample'
Run Code Online (Sandbox Code Playgroud)
从中.
for d, _, files in os.walk(path):
print(d[4]) # would be great to have something like this..
Run Code Online (Sandbox Code Playgroud)
怎么做得很好,也许有人知道?
非常感谢提前.
我有一个空数组.
我想分配一个像这样的值: array[key][subkey] = 'value'
这会产生KeyError,因为array [key]尚不存在.
我该怎么办?我试过以下......
array['key'] = None
array['key']['subkey'] = 'value'
Run Code Online (Sandbox Code Playgroud)
TypeError:'NoneType'对象不支持项目分配
我试过了:
array['key'] = []
array['key']['subkey'] = 'value'
Run Code Online (Sandbox Code Playgroud)
TypeError:list indices必须是整数,而不是str
我试过了:
array['key'] = ['subkey']
array['key']['subkey'] = 'value'
Run Code Online (Sandbox Code Playgroud)
TypeError:list indices必须是整数,而不是str
那我该怎么办?
如何编写函数以获取给定列表中索引a和b之间的项目的总和。例如Give aList=[6,3,4,2,5]
和a=1
,b=3
函数应该返回9。这是我的代码:
def sumRange(L,a,b):
sum= []
L = [6,3,4,2,5]
for i in range(a,b+1,1):
sum +=L[i]
return sum
Run Code Online (Sandbox Code Playgroud) 我试图在 python 中将纪元日期时间转换为字节数组,但它是 10 字节,它应该是 4 字节。
from time import time
curTime = int(time.time())
b = bytearray(str(curTime))
len(b) #comming as 10
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮助我出错的地方
python ×10
dictionary ×2
django ×2
python-2.7 ×2
date ×1
epoch ×1
indices ×1
list ×1
python-3.x ×1
range ×1
sequence ×1
sum ×1