简体   繁体   English

确定可迭代对象是python中的字符串还是列表

[英]Determining whether an iterable is a string or list in python

I've made an html page that has several checkboxes. 我制作了一个具有多个复选框的html页面。 Each value of a checkbox are two numbers separated by a question mark sign, ie "1?16". 复选框的每个值都是两个数字,中间用问号隔开,即“ 1?16”。

<input class="checkbox1" type="checkbox"  name ="nr_ids" id="checkbox_id" value ="1?16">Name1,16</label> <br>
<input class="checkbox1" type="checkbox"  name ="nr_ids" id="checkbox_id" value ="11?4">Name11,4</label> <br>

Then I read in this information using a python cgi: 然后,我使用python cgi读取了此信息:

NRs = form.getvalue("nr_ids")
NRids = []
for l in NRs:
    ls = l.split("?")
    NRids.append(ls)

NRs will be ['1?16', '11?4'] if you select both of them. 如果同时选择两个,则它们将为['1?16','11?4']。 If you select just one, it will be '2?14' 如果您只选择一个,则为“ 2?14”

What I wan is a list of lists, where each pair of numbers are subrows: [['1','16'],['11','4']]. 我想要的是一个列表列表,其中每对数字都是子行:[['1','16'],['11','4']]。 This works perfectly well if I select two or more checkboxes. 如果我选择两个或多个复选框,则效果很好。 However, I select just 1, the program crashes. 但是,我只选择1,程序崩溃。 NRids becomes [['1'], [','],['1'],['6']]. NRids变为[['1'],[','],['1'],['6']]。 When I try to take the type of the NRs, nothing prints. 当我尝试采用NR的类型时,没有任何显示。 I don't know how to automatically check to see if a string or a list has been passed in when they type function doesn't seem to be printing anything. 我不知道当他们键入函数似乎没有打印任何内容时,如何自动检查是否传递了字符串或列表。

How could I check to see if only one checkbox has been selected so I don't treat NRs like a list if it is not? 我如何检查是否仅选中了一个复选框,所以如果没有选中,则不将NR视为列表? Or does anyone have any other suggestions for how I can fix this? 还是有人对我如何解决此问题有其他建议?

if isinstance(a_variable,basestring):
   #its a string of sorts
elif isinstance(a_variable,(list,tuple)):
   #its a list or table

I guess? 我猜?

If the processing code is not completely trivial, a nice idiom is to check the type early and convert the simpler case to the more general case; 如果处理代码不是完全无关紧要的,那么一个不错的习惯用法就是尽早检查类型并将较简单的情况转换为更一般的情况; in this case, if the value is not a list, convert it to a one-element list. 在这种情况下,如果该值不是列表,则将其转换为一个元素列表。 The rest of the code can then rely on getting a list, sparing you the need to Repeat Yourself: 然后,其余代码可以依赖于获取列表,从而使您无需重复自己:

if not isinstance(NRs, list):
    NRs = [ NRs ]

# Now it's a list for sure...
for l in NRs:
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM