Итерировать таблицу и возвращать количество пар в списках в Python - PullRequest
0 голосов
/ 19 февраля 2020

Наличие столбца людей и столбца, скажем, местоположений этих людей, где их местоположения упорядочены по времени, например:

People=["A", "A", "B", "B", "B", "C", "C", "C"]
Location=["GA", "IL", "GA", "IL", "GA", "CA", "IL", "GA"]

Как бы вы запрограммировали итерацию, которая возвращает это:

Change_of_location=["GA-IL","IL-GA","CA-IL] и count=[2, 2, 1], поскольку пара "GA-IL" появляется дважды и т. c. То есть итерация должна возвращать выполненные поездки (изменение местоположения) на основе строк местоположений людей.

Ответы [ 2 ]

1 голос
/ 19 февраля 2020

Я буду использовать рецепт, основанный на инструменте zip .

people = ["A", "A", "B", "B", "B", "C", "C", "C"]
location = ["GA", "IL", "GA", "IL", "GA", "CA", "IL", "GA"]

chg_of_loc = {}

for first, second, loc1, loc2 in zip(people, people[1:], location, location[1:]):
    # if version(python) < 3.6 use format 
    start_end = f'{loc1}-{loc2}'
    if first == second:
        chg_of_loc[start_end] = chg_of_loc.get(start_end, 0) + 1


print(f"Change={list(chg_of_loc.keys())} and count={list(chg_of_loc.values())}")
0 голосов
/ 20 февраля 2020

Я собрал простой код, который, кажется, делает это в Python 3.6.

#PYTHON 3.6

# Input arrays
people = ["A", "A", "B", "B", "B", "C", "C", "C"]
location = ["GA", "IL", "GA", "IL", "GA", "CA", "IL", "GA"]

# Output arrays
Change_of_location = []
count = []

# Other variables
temp = []           # Temporary array for storing sorted values
lastPerson = ''     # String for storing last person in array
cnt = 0             # Counter for cycling through array

# Cycle through the records of people
for i in people:
    # Check if the current person is the same as the last
    if lastPerson == people[cnt]:
        # Save the locations travelled by this person
        temp.append(location[cnt-1] + '-' + location[cnt])
    # Update the last person and increment the counter
    lastPerson = people[cnt]
    cnt+=1

# Sort the temporary array
temp.sort()

# Create a counter variable for cycling through the temporary array,
#  a variable for counting the number of trips, and a string to store
#  the last trip
cnt2 = 0
cntTrip = 1
lastTrip = ''

# Cycle through the temporary array
for i in temp:
    # check if the current trip is the same as the last
    if lastTrip == temp[cnt2]:
        # increment the counter
        cntTrip+=1
    # else, check if the last trip string is empty (first iter)
    elif lastTrip != temp[cnt2] and lastTrip != '':
        # append trip to array
        Change_of_location.append(lastTrip)
        # append trip count to array
        count.append(cntTrip)
        # reset the trip counter to 1
        cntTrip = 1
    # set the last trip to the current trip
    lastTrip = temp[cnt2]
    # increment the counter
    cnt2+=1

# Append the last values from the temporary array
Change_of_location.append(lastTrip)
count.append(cntTrip)

# Print the results
print(Change_of_location)
print(count)

Определенно есть более эффективный способ сделать это; но это работает и не зависит от импорта.

Вывод: Change_of_location = ['CA-IL','GA-IL','IL-GA'] и count = [1,2,2]

...