我有一个元组列表
居:
public ActionResult Create()
{
//will contain the list of CategorytNames and it will bind this on the Create.
//cshtml view as given below
ViewBag.CategoryID = new SelectList(db.Categories, "Id", "CategoryName");
return View();
}
public ActionResult Edit(int id = 0)
{
FoodMenuItem foodmenuitem = db.FoodMenuItems.Find(id);
if (foodmenuitem == null)
{
return HttpNotFound();
}
//checking what the selected value was using LINQ query and then using that value inside SelectList.
//Now, DropDownList will look at the provided default selected value and displays it
int selected = (from cat in db.FoodMenuItems
where cat.ID == id
select cat.CategoryID).First();
ViewBag.CategoryID = new SelectList(db.Categories, "Id", "CategoryName", selected);
// ViewBag.CategoryID = new SelectList(db.Categories, "Id", "CategoryName", foodmenuitem.CategoryID);
return View(foodmenuitem);
}
元组的长度并不总是相同的。在示例中是5但可以更改
我找到了一个元素(部分元组)。
元素的长度并不总是相同。
我正在寻找元组中元素的位置。
要查找的元素的长度始终小于或等于元组的长度。
要查找的项目的顺序是“正确的”,这意味着类型('m','o')的案例不存在
居:
[('a','b','c','d','e'),
('f','g','h','i','l'),
('m','n','o','p','q'),
('r','s','t','u','v'),
('z', 'aa', 'ab', 'ac', 'ad'),
.....]
答案 0 :(得分:1)
正如@tobias_k建议的那样,最简单的方法是将元组和子元素转换为字符串,并使用in
运算符进行子字符串检查:
l = [('a','b','c','d','e'),
('f','g','h','i','l'),
('m','n','o','p','q'),
('r','s','t','u','v'),
('z', 'aa', 'ab', 'ac', 'ad'),
...]
def subtuple_index(tuples, t):
def tuple2str(t): return ',{},'.format(','.join(t))
t = tuple2str(t)
for i,x in enumerate(map(tuple2str, tuples)):
if t in x: return i
return -1
>>> subtuple_index(l, ('m','n'))
2
>>> subtuple_index(l, ('z','aa','ab'))
4
>>> subtuple_index(l, ('m','o'))
-1
>>> subtuple_index(l, ('z','a'))
-1
答案 1 :(得分:-1)
如前所述,将元组转换为字符串要容易得多:
tuple_list = [('a','b','c','d','e'),
('f','g','h','i','l'),
('m','n','o','p','q'),
('r','s','t','u','v'),
('z', 'aa', 'ab', 'ac', 'ad'),
...]
def find_tuple(tuplist, *partial_elements):
for tup in tuplist:
tup_string = ',{0},'.format(','.join(tup))
if ',{0},'.format(','.join(partial_elements)) in tup_string:
return tuplist.index(tup)
find_tuple(tuple_list, 'm', 'n') -> 2
find_tuple(tuple_list, 'z', 'aa', 'ab') -> 4
请注意,这只会返回它在找到部分元素的列表中找到的第一个元组的索引。