2015-07-13 92 views
0

当我运行下面的代码:排号蟒阵列

array1 = ["happy", "sad","good", "bad","like"] 
array2=["i like starhub", "i am happy with the starhub service", "starhub is  bad"," this is not awful"] 

for i in array1: 
    for j in array2: 
     if i in j : 
      print i 

印刷将是

happy 
bad 
like 

输出根据他们在array1列出的顺序打印的结果。我如何根据array2对输出进行排序?我想输出是:

like 
happy 
bad 

回答

1

Leb的答案是正确的钱;请注册并接受它。

我只想添加关于命名约定的注释。

在许多编程语言中,变量名称ij传统上用于数字循环索引,但不适用于列表或数组中元素的实际值。

例如(双关语意),如果你正在写在JavaScript老式for循环,它可能是这样的:

var names = [ "Kent", "Leb", "Dalen" ]; 
for(var i = 0; i < names.length; i++) { 
    console.log(names[i]); 
} 

你也可以这样写在Python代码,但因为你'使用更具表现力的Python for循环,您可以使用比ij更好的名称。

由于达伦的评论指出,该名array1array2不匹配的Python术语—但更重要的是,他们没有说什么是这些列表什么。

在整个过程中使用更多不言自明的变量名是有帮助的。在你的代码中,这两个列表是一个单词列表和一个短语列表,循环中的变量代表单个单词和单个短语。

我在这里喜欢的约定是使用复数名称作为列表或数组,以及该列表或数组的单个元素的相应单数名称。

所以,你可以使用的名称是这样的:

words = [ "happy", "sad", "good", "bad", "like" ] 
phrases = [ 
    "i like starhub", 
    "i am happy with the starhub service", 
    "starhub is bad", 
    " this is not awful" 
] 

for phrase in phrases: 
    for word in words: 
     if word in phrase: 
      print(word) 

你看到多少更加清晰,这使得代码?而不是ijarray1array2(或list1list2),每个名称都描述了您正在使用的实际数据。

4

开关循环:

list1 = ["happy", "sad", "good", "bad", "like"] 
list2 = ["i like starhub", "i am happy with the starhub service", "starhub is bad", " this is not awful"] 

for j in list2: 
    for i in list1: 
     if i in j: 
      print(i) 


>>like 
>>happy 
>>bad 

在顶部的一个被什么东西被作为主要的清单。所以在你的情况下,list1是主要的,正在排序。

在我给的那个,list2是主要的。

+0

你在这里使用的不是数组。这些是列表。 Python中的数组是:“import array; a1 = array.array([1,2,3])”。请修改您的帖子,以免它人混淆。 – Dalen

+0

你是对的,谢谢你提醒我注意。 – Leb

+0

Woops,它的:array.array(“h”,[1,2,3])。对不起,忘了你必须指定类型。 – Dalen