知道aPython列表是否有一个项目或多个项目

时间:2017-01-27 19:25:31

标签: python-2.7

说我有两种可能性,我事先也不知道。 A = [" abc"," def"," ghi"]或A =" abc"。

如果列表长度超过一个,我想做点什么。 我不能简单地做"如果len(A)> 1做到这一点"因为这两个条件都满足这个要求。

我想以某种方式区分这两种可能性。如何在Python中做到这一点?

谢谢

以下是已编辑的\添加部分..

当你看到输出的第一行..而不是显示[[无,晚餐]] 显示[[无,' d'],[无,'我'],[无,' n'],[无,' n& #39;],[无,' e'],[无,' r']]

如何解决这个问题?我哪里错了? 真的很抱歉这个令人困惑的帖子和编辑帖已经有几条评论......

以下代码

menu = {'dinner':
        {'chicken':'good',
         'beef':'average',
         'vegetarian':{
               'tofu':'good',
               'salad':{
                        'caeser':'bad',
                        'italian':'average'}
               },
         'pork':'bad'}
    }
vertices, edges = [],[]
counter = 1
def TranverseTheTree(DictTree, parent=None):
    for edge, vertex in DictTree.iteritems():
        if isinstance(vertex, dict):
            global counter
            counter += 1
            vertices.append(vertex.keys())
            edges.append([[parent,i] if len(edge)>1 else [parent,edge] for i in edge])
            TranverseTheTree(vertex, edge)
        else:
            vertices.append(vertex)
            edges.append([vertex, edge])

TranverseTheTree(menu)
for each in edges:
    print each

下面的输出
[[None, 'd'], [None, 'i'], [None, 'n'], [None, 'n'], [None, 'e'], [None, 'r']]
['bad', 'pork']
['good', 'chicken']
[['dinner', 'v'], ['dinner', 'e'], ['dinner', 'g'], ['dinner', 'e'], ['dinner', 't'], ['dinner', 'a'], ['dinner', 'r'], ['dinner', 'i'], ['dinner', 'a'], ['dinner', 'n']]
['good', 'tofu']
[['vegetarian', 's'], ['vegetarian', 'a'], ['vegetarian', 'l'], ['vegetarian', 'a'], ['vegetarian', 'd']]
['average', 'italian']
['bad', 'caeser']
['average', 'beef']

处理完成,退出代码为0

1 个答案:

答案 0 :(得分:0)

在第一种情况下,Alist,在第二种情况下,它是string。所以你可以通过

来区分它们
if type(A) == list:
    # do something
elif type(A) == str:
    # do something else
else:
    # don't do anything