附加条件



我要写一个程序,取一些行并将它们转换成一行,但不幸的是,我有一个附加不常见元素的问题。这是我目前所做的:

List_of_sentences = []
for line in range(int(input())):
List_of_sentences.append(input().strip().split())
Sample_sentence = input().split()
Final_list = []
for lists in List_of_sentences:
for elements in Sample_sentence:
if elements in lists:
Final_list.append(lists[0])
else:
Final_list.append(elements)

print(' '.join(Final_list))

以为例,考虑以下两个列表:

List_of_sentences = [['man', 'I', 'je', 'ich'], ['kheili', 'very', 'très', 'sehr'], ['alaghemand', 'interested', 'intéressé', 'interessiert'], ['barnamenevisi', 'programming', 'laprogrammation', 'Programmierung']]
Sample_sentence = ['I', 'am', 'very', 'interested', 'in', 'programming']

它必须返回这个:

man am kheili alaghemand in barnamenevisi

,而是:

man kheili alaghemand barnamenevisi

我的问题是else部分

任何帮助都是非常感谢的

你的循环看起来有点乱。应该是这样的顺序

List_of_sentences = []
for line in range(int(input())):
List_of_sentences.append(input().strip().split())
Sample_sentence = input().split()
Final_list = []
for elements in Sample_sentence: #this for loop should be first
var = None
for lists in List_of_sentences: # this for loop should be second
if elements in lists:
#Final_list.append(lists[0])
var = lists[0]
break
Final_list.append(var if var else elements)

print(' '.join(Final_list))

这是我尝试过的,它是有效的:

List_of_sentences = [
['man', 'I', 'je', 'ich'], 
['kheili', 'very', 'très', 'sehr'], 
['alaghemand', 'interested', 'intéressé', 'interessiert'], 
['barnamenevisi', 'programming', 'laprogrammation', 'Programmierung']
]
Sample_sentence = ['I', 'am', 'very', 'interested', 'in', 'programming']
Final_list = []
for elements in Sample_sentence:
found = False
for lists in List_of_sentences:
if elements in lists:
Final_list.append(lists[0])
found = True
if not found:
Final_list.append(elements)
print(' '.join(Final_list))

你的代码的问题是,它总是添加一个元素,如果它没有找到,而不是添加一次,并继续下一个元素

您可以尝试这样做:

for elements in Sample_sentence: # since you need to check for elements in the sample sentence in all lists, this should be the outer loop
present = False
for lists in List_of_sentences:
if elements in lists:
Final_list.append(lists[0])
present = True
if not present:
Final_list.append(elements)

这对我有用

for word in Sample_sentence:
append = False
for list in List_of_sentences:
for translation in list:
if (translation == word):
Final_list.append(list[0])
append = True
if (not append):
Final_list.append(word)

print(' '.join(Final_list))

输出是这样的,因为您遍历每个列表,对于每个列表,您遍历样本句子中的每个元素,因此,首先,它将搜索样本句子中的任何元素是否在第一个列表中匹配("I";将匹配),然后它将插入列表的第一个元素,即"man"在最后的列表中。对于第二个列表"非常"因此,它将插入第二个列表的第一个元素,即"kheili"在最后的列表中。因此,最终列表将是这样的:["man", "kheili"…,这就是你得到的。这解释了您遇到的问题。

最新更新