[英]To identify repeated words and get the distance between two words as a list in python
[英]How to get a sublist of a list between two words
从这样的列表开始:
words = ['tree', 'water', 'dog', 'soap', 'bike', 'cat', 'bird']
我想获取两个指定单词之间的子列表。 例如,如果我有'water'
和'bike'
这两个词,我想获得子列表:
words = ['water', 'dog', 'soap', 'bike']
或者如果列表是
words = ['tree', 'water', 'dog', 'soap', 'tree', 'cat', 'bird']
我把'tree'
和'tree'
这两个'tree'
我想得到这个子列表:
words = ['tree', 'water', 'dog', 'soap', 'tree']
我也用 C 写了一个这样的程序,但我现在对 Python 不是很好。 这是我的 C 版本:
struct node {
char *key;
struct node *next;
struct node *prev;
};
typedef struct node node;
node *GetSublist(node *, char *, char *);
node *MakeStringList();
void PrintStringList(node *a);
node *GetSublist(node *a, char *k1, char *k2) {
node *p = a;
node *n1, *n2;
while (strcmp(p->key, k1) != 0) {
p = p->next;
if (p == NULL) {
return a;
}
}
n1 = p;
n2 = p->next;
if (n1->prev != NULL) {
while (a != n1) {
free(a);
a = a->next;
}
}
a->prev = NULL;
while (strcmp(n2->key, k2) != 0) {
n2 = n2->next;
if (n2 == NULL) {
return a;
}
}
if (n2->next != NULL) {
while (n2->next == NULL) {
free(n2->next);
n2 = n2->next;
}
n2->next = NULL;
}
return a;
}
int main(){
char *k1 = "dog";
char *k2 = "ball";
node *list1 = NULL;
list1 = MakeStringList();
PrintStringList(list1);
list1 = GetSublist(list1, k1, k2);
PrintStringList(list1);
return 0;
}
node *MakeStringList() {
node *a = NULL, *punt, *p;
int i;
int dim;
printf("Number of elements: ");
scanf("%d", &dim);
for (i=0; i<dim; i=i+1) {
punt = malloc( sizeof(node) );
punt->key = (char*)malloc(30*sizeof(char));
scanf( "%s", punt->key );
punt->next = NULL;
punt->prev = NULL;
if(a == NULL) {
a = punt;
p = punt;
} else {
p->next = punt;
punt->prev = p;
p = punt;
}
}
return a;
}
void PrintStringList(node *a) {
node *p = a;
printf("\nThe list is: { ");
while( p != NULL ) {
if (p->next == NULL)
printf("%s ", p->key);
else
printf("%s, ", p->key);
p = p->next;
}
printf("}\n\n");
}
这可以通过列表的.index()
方法和切片符号来完成。
words = ['tree', 'water', 'dog', 'soap', 'cat', 'bird']
start_index = words.index(start_word)
end_index = words.index(end_word)
sublist = words[start_index:end_index+1]
def sublist_two_words(array, start_word, end_word):
result = []
for word in array:
if result or word == start_word:
result.push(word)
if word == end_word:
break
return result
这样即使没有end_word
它end_word
得到整个剩余的列表。 如果我正确地完成了你的任务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.